# Thread: Help - Bit Manipulation

1. ## Help - Bit Manipulation

I am trying to set a hex value to a variable and then convert that value to bits. I then need to set a value to another variable with the reverse bits.

For example:

x = 0x13fa

Converted, this would equal (not accurate, but for arguments sake):

0001 0011 1111 1001

I need to convert this to:

1001 1111 1100 1000

I am having trouble with the conversion. I've been trying to use a loop like y = x<<15. y = y + x<<14, etc. but this is not working.

Thanks so much.

2. Ignoring that a != 1001, as you stated, there has been past discussion of reversing the order of a string. Just a guess.

3. This should work, but there might be better ways to do this. The PowerOf2() function should return 2^x (ie: 2^0 = 1, 2^1 =2, 2^2 = 4...). There is an existing function for this, but I can't remember its name. Pow() something.
Code:
const int SizeOfInt 16;
int Variable = *whatever*;
int TempVariable = 0;

for(int i=0; i<SizeofInt; i++)
{
if(Variable & PowerOf2(i)) TempVariable |= PowerOf2(SizeOfInt - 1 - i);
}

Variable = TempVariable;

4. Don't use an 'if'. There is no reason to test for the state of the bit. simply zero your scratch space, and mask for the '1' values and shift them into place. The zero bits will take care of themselves.

5. Try this.
Code:
int x = 0xaaaa;
int flip = 0;
int i, temp;

printf("x:%X\n",x);
temp = x;
for (i=0; i<16; i++)
{
flip <<= 1;
temp >>= 1;
}
printf("flip:%X\n",flip);

6. Darn, I had to go out so I'm too late - but what the heck:
--------------------------------------------------------

#include<stdio.h>
#include<math.h>

int main(void)
{
unsigned short int a, b=0, temp; /*16 bits */
int i;
float power; /* return type of pow() */

a = 0x13F9; /*hex number to be reversed bit by bit */

for (i=0; i<16; i++) /*16 bits */
{
power = pow(2, i); /* from 1 to 32768 */
/* work from right to left looking at each bit */
temp = a & (unsigned short int)power;
if (temp > 0) /*a 1 was encountered */
{
/* work from left to right XORing 1's in */
power = pow(2, 15-i);
b = b ^ (unsigned short int)power;
}
}

printf("\n%x %x", a, b);
return 0;
}