I\'m converting an unsigned integer to binary using bitwise operators, and currently do integer & 1 to check if bit is 1 or 0 and output, then right shift by 1 to divide
The Best way to reverse the bit in an integer is:
CODE SNIPPET
int reverse ( unsigned int n )
{
int x = 0;
int mask = 1;
while ( n > 0 )
{
x = x << 1;
if ( mask & n )
x = x | 1;
n = n >> 1;
}
return x;
}
The 2nd answer by Dietrich Epp is likely what's best on a modern processor with high speed caches. On typical microcontrollers however that is not the case and there the following is not only much faster but also more versatile and more compact (in C):
// reverse a byte
uint8_t reverse_u8(uint8_t x)
{
const unsigned char * rev = "\x0\x8\x4\xC\x2\xA\x6\xE\x1\x9\x5\xD\x3\xB\x7\xF";
return rev[(x & 0xF0) >> 4] | (rev[x & 0x0F] << 4);
}
// reverse a word
uint16_t reverse_u16(uint16_t x)
{
return reverse_u8(x >> 8) | (reverse_u8(x & 0xFF) << 8);
}
// reverse a long
uint32_t reverse_u32(uint32_t x)
{
return reverse_u16(x >> 16) | (reverse_u16(x & 0xFFFF) << 16);
}
The code is easily translated to Java, Go, Rust etc. Of course if you only need to print the digits, it is best to simply print in reverse order (see the answer by Dietrich Epp).
you could move from left to right instead, that is shift a one from the MSB to the LSB, for example:
unsigned n = 20543;
unsigned x = 1<<31;
while (x) {
printf("%u ", (x&n)!=0);
x = x>>1;
}
You could just loop through the bits from big end to little end.
#define N_BITS (sizeof(unsigned) * CHAR_BIT)
#define HI_BIT (1 << (N_BITS - 1))
for (int i = 0; i < N_BITS; i++) {
printf("%d", !!(x & HI_BIT));
x <<= 1;
}
Where !!
can also be written !=0
or >> (N_BITS - 1)
.
I came up with a solution which dosesn't involve any application of bitwise operators. it is inefficient in terms of both space and time.
int arr[32];
for(int i=0;i<32;i++)
{
arr[i]=A%2;
A=A/2;
}
double res=1;
double re=0;
for(int i=0;i<32;i++)
{
int j=31-i;
res=arr[i];
while(j>0)
{
res=res*2;
j--;
}
re=re+res;
}
cout<<(unsigned int )re;
unsigned int rev_bits(unsigned int input)
{
unsigned int output = 0;
unsigned int n = sizeof(input) << 3;
unsigned int i = 0;
for (i = 0; i < n; i++)
if ((input >> i) & 0x1)
output |= (0x1 << (n - 1 - i));
return output;
}