Related
A binary number is normally stored with a fixed position MSB and a LSB; from LSB to MSB the weighting is doubled each bit. Are there any other ways of storing a binary number?
the traditional way may be the most efficient way, when requiring the lowest number of logical electronic bits needed to represent a number, but there are some disadvantages with this method. One disadvantage is that when sequentially counting the toggling of the LSB is quite high because it toggles state on each incremental count.
I was trying to scramble the weighting of each bit so that when sequentially counting, each bit that represents the binary number has the same amount of toggling. There are many advantages for achieving this method, even though more bits are required for the number.
One advantage is that the life of EEPROM would be extended because an equal amount of toggling occurs in all of the physical cells that represent the stored number. Another advantages when overclocking a cpu, error correction, and more.
If a oscilloscope probe examines a traditional address bus, the LSB has a lot of HARD work, and the MSB is very idle.
traditional method:
(number)
0000
0001
0010
0011
0100
new proposed method:
(scramble encoder)(number)
How about a binary number system like this? When counting with a very high bus speed, the transistors do not overheat and therefore limit clock speed.
The solution uses both base-2 and base-1 binary to make a number.
((base-2 binary number)*size_of_in_bits(base-1 binary number)) + base-1 binary number
so for a 16 bit bus, with the high byte binary base-2, and the low byte binary base-1, the maximum count would be
((2^8)-1)*8)+8) = 2048
The solution to the EEPROM life problem could be:
Using a EEPROM that only changes the required cells when writing new data to maximise life.
4 bytes (32bit) for the base-2 part of the number, and 13 bytes (100 bit) for the base-1 part of the number.
((32 bit base-2 binary number) x 100) + (100 bit binary base-1 tally counter)
The maximum count would be (((2^32)-1) *100)+100) = 429,496,729,700
This method should get the maximum life from the EEPROM or FLASH memory, for FLASH memory the base-1 number should be stored inverted, because the erased state is logic 1.
The EEPROM can, read, increment, write, a number 2 orders of magnitude bigger, achieving a count of 1 million instead of ten thousand.
Send me a email and I can give you the program, it works in MVS 2013 console.
lion#palmbeach.freeserve.co.uk
/* a www.goatelectronics.com solution */
/* This program is designed to test eeprom life, writing to the same page and cells */
/* 32 bit base-2 binary number + 100 bit base-1 binary number make the number*/
/* byte 0 - Most significant byte , binary base-2 number */
/* byte 1 - */
/* byte 2 - */
/* byte 3 - Least significant byte, binary base-2 number */
/* byte 4 - 8 bit CRC suffix for 32bit number, to be done later */
/* byte 5 - count 0 to 8 of binary base-1 number */
/* byte 6 - count 9 to 16 of binary base-1 number*/
/* byte 7 - count 17 to 24 of ... */
/* byte 8 - count 25 to 32 */
/* byte 9 - count 33 to 40 */
/* byte 10 - count 41 to 48 */
/* byte 11 - count 49 to 56 */
/* byte 12 - count 57 to 64 */
/* byte 13 - count 65 to 72 */
/* byte 14 - count 73 to 80 */
/* byte 15 - count 81 to 88 */
/* byte 16 - count 89 to 96 */
/* byte 17 - count 97 to 100 */
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
/* emulate the eeprom *here* , byte read and write */
unsigned char eeprom[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned int EEPROM_read (void)
{
unsigned char i_u8;
unsigned int value_u32, value_A_u32, value_B_u32, value_C_u32, value_D_u32 = 0;
unsigned int base_1_u32 = 0;
value_A_u32 = eeprom[0];
value_A_u32 = value_A_u32 << 24;
value_B_u32 = eeprom[1];
value_B_u32 = value_B_u32 << 16;
value_C_u32 = eeprom[2];
value_C_u32 = value_C_u32 << 8;
value_D_u32 = eeprom[3];
value_u32 = value_A_u32 | value_B_u32 | value_C_u32 | value_D_u32;
/* eeprom[4] reserved location for CRC checksum! */
value_u32 = value_u32 * 100;
for (i_u8 = 5; eeprom[i_u8] == 0xFF; i_u8++)
{
base_1_u32 = base_1_u32 + 8;
}
switch (eeprom[i_u8])
{
case 0x80: base_1_u32 = base_1_u32 + 1;
break;
case 0xC0: base_1_u32 = base_1_u32 + 2;
break;
case 0xE0: base_1_u32 = base_1_u32 + 3;
break;
case 0xF0: base_1_u32 = base_1_u32 + 4;
break;
case 0xF8: base_1_u32 = base_1_u32 + 5;
break;
case 0xFC: base_1_u32 = base_1_u32 + 6;
break;
case 0xFE: base_1_u32 = base_1_u32 + 7;
break;
default:; /*if here, faulty EEPROM with base-1 number*/
}
value_u32 = value_u32 + base_1_u32;
return (value_u32);
}
void EEPROM_write(unsigned int number_u32)
{
unsigned char i_u8, remainder_u8;
unsigned int value_u32;
value_u32 = number_u32;
value_u32 = value_u32 / 100;
eeprom[0] = (unsigned char)((value_u32 & 0xFF000000) >> 24);
eeprom[1] = (unsigned char)((value_u32 & 0x00FF0000) >> 16);
eeprom[2] = (unsigned char)((value_u32 & 0x0000FF00) >> 8);
eeprom[3] = (unsigned char)((value_u32 & 0x000000FF));
remainder_u8 = (unsigned char)(number_u32 % 100);
if (!remainder_u8)
{
for (i_u8 = 5; i_u8 < 18; i_u8++)
{
eeprom[i_u8] = 0x00;
}
}
for (i_u8 = 5; remainder_u8 >=8; i_u8++)
{
eeprom[i_u8] = 0xFF;
remainder_u8 = remainder_u8 - 8;
}
switch (remainder_u8)
{
case 1: eeprom[i_u8] = 0x80;
break;
case 2: eeprom[i_u8] = 0xC0;
break;
case 3: eeprom[i_u8] = 0xE0;
break;
case 4: eeprom[i_u8] = 0xF0;
break;
case 5: eeprom[i_u8] = 0xF8;
break;
case 6: eeprom[i_u8] = 0xFC;
break;
case 7: eeprom[i_u8] = 0xFE;
break;
default:; /**/
}
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned char i_u8;
unsigned int test_number_u32;
unsigned int loop_u32 = 0;
while (loop_u32 <0xFFFFFFFF)
{
test_number_u32 = EEPROM_read();
test_number_u32++;
EEPROM_write(test_number_u32);
for (i_u8 = 0; i_u8 < 18; i_u8++)
{
printf(" %x", eeprom[i_u8]);
}
printf(" \n");
loop_u32++;
}
I am going over some revision and I came across a question that asked what is 10011001 in signed integer and unsigned. I know the unsigned integer is 153 because there are no negatives in unsigned integers, but am I correct to say the signed integer of 10011001 is -153 or am I making a mistake ?
This difference between unsigned and signed number is that one of the bit is used to indicate positive or negative number.
So in your example you have 8 bits.
If I treat is as signed, then I have 7 bits to work with: 2^7
000 0000 = 0
111 1111 = 127
001 1001 = 25 then the most significant bit cause the following calculation to occurred.
(25 - 128) = -103
If I use all 8 bits then I unsigned bits to work with: 2^8
0000 0000 = 0
1111 1111 = 255
1001 1001 = 153
Here is code to demonstrate the answer:
char *endptr;
char binary[11] = "10011001"; // need an extra char for the termination
char x = (char)strtol(binary, &endptr, 2);
unsigned char y = (unsigned char)strtol(binary, &endptr, 2);
printf("%s to signed char (1 byte): %i\n", binary, (short)x);
printf("%s to unsigned char (1 byte): %u\n", binary, y);
Output:
Is there a algorithm or formula that can convert any base n, say 2 to 36, to binary? I've looked around the web and can't quite find what I'm looking for.
Something to get you started.
unsigned strtou(const char *s, unsigned base) {
unsigned y = 0;
while (*s) {
unsigned digit;
if (isdigit(*s)) digit = ch - '0';
else if (isupper(*s)) digit = ch - 'A' + 10;
else if (islower(*s)) digit = ch - 'a' + 10;
else Handle_IllegalDigit();
if (digit >= base) Handle_IllegalDigit();
y = y*base + digit;
s++;
}
return y;
}
In the google protocol buffers encoding overview, they introduce something called "Zig Zag Encoding", this takes signed numbers, which have a small magnitude, and creates a series of unsigned numbers which have a small magnitude.
For example
Encoded => Plain
0 => 0
1 => -1
2 => 1
3 => -2
4 => 2
5 => -3
6 => 3
And so on. The encoding function they give for this is rather clever, it's:
(n << 1) ^ (n >> 31) //for a 32 bit integer
I understand how this works, however, I cannot for the life of me figure out how to reverse this and decode it back into signed 32 bit integers
Try this one:
(n >> 1) ^ (-(n & 1))
Edit:
I'm posting some sample code for verification:
#include <stdio.h>
int main()
{
unsigned int n;
int r;
for(n = 0; n < 10; n++) {
r = (n >> 1) ^ (-(n & 1));
printf("%u => %d\n", n, r);
}
return 0;
}
I get following results:
0 => 0
1 => -1
2 => 1
3 => -2
4 => 2
5 => -3
6 => 3
7 => -4
8 => 4
9 => -5
Here's yet another way of doing the same, just for explanation purposes (you should obviously use 3lectrologos' one-liner).
You just have to notice that you xor with a number that is either all 1's (equivalent to bitwise not) or all 0's (equivalent to doing nothing). That's what (-(n & 1)) yields, or what is explained by google's "arithmetic shift" remark.
int zigzag_to_signed(unsigned int zigzag)
{
int abs = (int) (zigzag >> 1);
if (zigzag % 2)
return ~abs;
else
return abs;
}
unsigned int signed_to_zigzag(int signed)
{
unsigned int abs = (unsigned int) signed << 1;
if (signed < 0)
return ~abs;
else
return abs;
}
So in order to have lots of 0's on the most significant positions, zigzag encoding uses the LSB as sign bit, and the other bits as the absolute value (only for positive integers actually, and absolute value -1 for negative numbers due to 2's complement representation).
How about
(n>>1) - (n&1)*n
After fiddling with the accepted answer proposed by 3lectrologos, I couldn't get it to work when starting with unsigned longs (in C# -- compiler error). I came up with something similar instead:
( value >> 1 ) ^ ( ~( value & 1 ) + 1 )
This works great for any language that represents negative numbers in 2's compliment (e.g. .NET).
I have found a solution, unfortunately it's not the one line beauty I was hoping for:
uint signMask = u << 31;
int iSign = *((Int32*)&signMask);
iSign >>= 31;
signMask = *((UInt32*)&iSign);
UInt32 a = (u >> 1) ^ signMask;
return *((Int32*)&a);
I'm sure there's some super-efficient bitwise operations that do this faster, but the function is straightforward. Here's a python implementation:
def decode(n):
if (n < 0):
return (2 * abs(n)) - 1
else:
return 2 * n
>>> [decode(n) for n in [0,-1,1,-2,2,-3,3,-4,4]]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
If I have a integer number n, how can I find the next number k > n such that k = 2^i, with some i element of N by bitwise shifting or logic.
Example: If I have n = 123, how can I find k = 128, which is a power of two, and not 124 which is only divisible by two. This should be simple, but it eludes me.
For 32-bit integers, this is a simple and straightforward route:
unsigned int n;
n--;
n |= n >> 1; // Divide by 2^k for consecutive doublings of k up to 32,
n |= n >> 2; // and then or the results.
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++; // The result is a number of 1 bits equal to the number
// of bits in the original number, plus 1. That's the
// next highest power of 2.
Here's a more concrete example. Let's take the number 221, which is 11011101 in binary:
n--; // 1101 1101 --> 1101 1100
n |= n >> 1; // 1101 1100 | 0110 1110 = 1111 1110
n |= n >> 2; // 1111 1110 | 0011 1111 = 1111 1111
n |= n >> 4; // ...
n |= n >> 8;
n |= n >> 16; // 1111 1111 | 1111 1111 = 1111 1111
n++; // 1111 1111 --> 1 0000 0000
There's one bit in the ninth position, which represents 2^8, or 256, which is indeed the next largest power of 2. Each of the shifts overlaps all of the existing 1 bits in the number with some of the previously untouched zeroes, eventually producing a number of 1 bits equal to the number of bits in the original number. Adding one to that value produces a new power of 2.
Another example; we'll use 131, which is 10000011 in binary:
n--; // 1000 0011 --> 1000 0010
n |= n >> 1; // 1000 0010 | 0100 0001 = 1100 0011
n |= n >> 2; // 1100 0011 | 0011 0000 = 1111 0011
n |= n >> 4; // 1111 0011 | 0000 1111 = 1111 1111
n |= n >> 8; // ... (At this point all bits are 1, so further bitwise-or
n |= n >> 16; // operations produce no effect.)
n++; // 1111 1111 --> 1 0000 0000
And indeed, 256 is the next highest power of 2 from 131.
If the number of bits used to represent the integer is itself a power of 2, you can continue to extend this technique efficiently and indefinitely (for example, add a n >> 32 line for 64-bit integers).
There is actually a assembly solution for this (since the 80386 instruction set).
You can use the BSR (Bit Scan Reverse) instruction to scan for the most significant bit in your integer.
bsr scans the bits, starting at the
most significant bit, in the
doubleword operand or the second word.
If the bits are all zero, ZF is
cleared. Otherwise, ZF is set and the
bit index of the first set bit found,
while scanning in the reverse
direction, is loaded into the
destination register
(Extracted from: http://dlc.sun.com/pdf/802-1948/802-1948.pdf)
And than inc the result with 1.
so:
bsr ecx, eax //eax = number
jz #zero
mov eax, 2 // result set the second bit (instead of a inc ecx)
shl eax, ecx // and move it ecx times to the left
ret // result is in eax
#zero:
xor eax, eax
ret
In newer CPU's you can use the much faster lzcnt instruction (aka rep bsr). lzcnt does its job in a single cycle.
A more mathematical way, without loops:
public static int ByLogs(int n)
{
double y = Math.Floor(Math.Log(n, 2));
return (int)Math.Pow(2, y + 1);
}
Here's a logic answer:
function getK(int n)
{
int k = 1;
while (k < n)
k *= 2;
return k;
}
Here's John Feminella's answer implemented as a loop so it can handle Python's long integers:
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n+1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift <<= 1
return n + 1
It also returns faster if n is already a power of 2.
For Python >2.7, this is simpler and faster for most N:
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
return 2**(n-1).bit_length()
This answer is based on constexpr to prevent any computing at runtime when the function parameter is passed as const
Greater than / Greater than or equal to
The following snippets are for the next number k > n such that k = 2^i
(n=123 => k=128, n=128 => k=256) as specified by OP.
If you want the smallest power of 2 greater than OR equal to n then just replace __builtin_clzll(n) by __builtin_clzll(n-1) in the following snippets.
C++11 using GCC or Clang (64 bits)
#include <cstdint> // uint64_t
constexpr uint64_t nextPowerOfTwo64 (uint64_t n)
{
return 1ULL << (sizeof(uint64_t) * 8 - __builtin_clzll(n));
}
Enhancement using CHAR_BIT as proposed by martinec
#include <cstdint>
constexpr uint64_t nextPowerOfTwo64 (uint64_t n)
{
return 1ULL << (sizeof(uint64_t) * CHAR_BIT - __builtin_clzll(n));
}
C++17 using GCC or Clang (from 8 to 128 bits)
#include <cstdint>
template <typename T>
constexpr T nextPowerOfTwo64 (T n)
{
T clz = 0;
if constexpr (sizeof(T) <= 32)
clz = __builtin_clzl(n); // unsigned long
else if (sizeof(T) <= 64)
clz = __builtin_clzll(n); // unsigned long long
else { // See https://stackoverflow.com/a/40528716
uint64_t hi = n >> 64;
uint64_t lo = (hi == 0) ? n : -1ULL;
clz = _lzcnt_u64(hi) + _lzcnt_u64(lo);
}
return T{1} << (CHAR_BIT * sizeof(T) - clz);
}
Other compilers
If you use a compiler other than GCC or Clang, please visit the Wikipedia page listing the Count Leading Zeroes bitwise functions:
Visual C++ 2005 => Replace __builtin_clzl() by _BitScanForward()
Visual C++ 2008 => Replace __builtin_clzl() by __lzcnt()
icc => Replace __builtin_clzl() by _bit_scan_forward
GHC (Haskell) => Replace __builtin_clzl() by countLeadingZeros()
Contribution welcome
Please propose improvements within the comments. Also propose alternative for the compiler you use, or your programming language...
See also similar answers
nulleight's answer
ydroneaud's answer
Here's a wild one that has no loops, but uses an intermediate float.
// compute k = nextpowerof2(n)
if (n > 1)
{
float f = (float) n;
unsigned int const t = 1U << ((*(unsigned int *)&f >> 23) - 0x7f);
k = t << (t < n);
}
else k = 1;
This, and many other bit-twiddling hacks, including the on submitted by John Feminella, can be found here.
assume x is not negative.
int pot = Integer.highestOneBit(x);
if (pot != x) {
pot *= 2;
}
If you use GCC, MinGW or Clang:
template <typename T>
T nextPow2(T in)
{
return (in & (T)(in - 1)) ? (1U << (sizeof(T) * 8 - __builtin_clz(in))) : in;
}
If you use Microsoft Visual C++, use function _BitScanForward() to replace __builtin_clz().
function Pow2Thing(int n)
{
x = 1;
while (n>0)
{
n/=2;
x*=2;
}
return x;
}
Bit-twiddling, you say?
long int pow_2_ceil(long int t) {
if (t == 0) return 1;
if (t != (t & -t)) {
do {
t -= t & -t;
} while (t != (t & -t));
t <<= 1;
}
return t;
}
Each loop strips the least-significant 1-bit directly. N.B. This only works where signed numbers are encoded in two's complement.
What about something like this:
int pot = 1;
for (int i = 0; i < 31; i++, pot <<= 1)
if (pot >= x)
break;
You just need to find the most significant bit and shift it left once. Here's a Python implementation. I think x86 has an instruction to get the MSB, but here I'm implementing it all in straight Python. Once you have the MSB it's easy.
>>> def msb(n):
... result = -1
... index = 0
... while n:
... bit = 1 << index
... if bit & n:
... result = index
... n &= ~bit
... index += 1
... return result
...
>>> def next_pow(n):
... return 1 << (msb(n) + 1)
...
>>> next_pow(1)
2
>>> next_pow(2)
4
>>> next_pow(3)
4
>>> next_pow(4)
8
>>> next_pow(123)
128
>>> next_pow(222)
256
>>>
Forget this! It uses loop !
unsigned int nextPowerOf2 ( unsigned int u)
{
unsigned int v = 0x80000000; // supposed 32-bit unsigned int
if (u < v) {
while (v > u) v = v >> 1;
}
return (v << 1); // return 0 if number is too big
}
private static int nextHighestPower(int number){
if((number & number-1)==0){
return number;
}
else{
int count=0;
while(number!=0){
number=number>>1;
count++;
}
return 1<<count;
}
}
// n is the number
int min = (n&-n);
int nextPowerOfTwo = n+min;
#define nextPowerOf2(x, n) (x + (n-1)) & ~(n-1)
or even
#define nextPowerOf2(x, n) x + (x & (n-1))