• C

# bit change

i have binary number like this
1 0 1 1 1 0 1 0
i need to chage the bit value like  bit 8 to bit 1
bit 7 to bit2
bit 6 to bit 3
bit 5 to bit 4
when changed the binary number will become 0 1 0 1 1 1 0 1
how to implemnt this using the bit operators
###### Who is Participating?

Commented:
Another nice way is
value = (value << 4) | (value>>4);
value = ((vaue&0x33)<< 2) | ((value>>2)&0x33);
value = ((vaue&0x55)<<1) | ((value>>1)&0x55);
0

Commented:
depends on your libraries, but these should help.
You could use assembler, as this has rotate functions...

david.tribble.com/text/c0xrot.htm
www.devx.com/tips/Tip/14043

Then I found this...
http://forums.devarticles.com/c-c-help-52/c-code-to-rotate-a-bit-in-a-given-number-50277.html

Hope that helps.
0

Commented:
The fastest way is probably with a 256 byte lookup table with all the reversed numbers pre computed
0

Author Commented:
i need to he exchange the bit position like shown below
the bibnary number is
b7  b6  b5  b4  b3  b2  b1  b0
after the exchangeof the bits  the binary number will be
b0  b1  b2  b3  b4  b5  b6  b7
what will be the fastest implementation
0

Commented:
>> what will be the fastest implementation

0

Author Commented:
i want a generic implementation that wil work for all the numbers
0

Commented:
>> i want a generic implementation that wil work for all the numbers

Both solutions shown by ozo are generic. The lookup table, as ozo said, is the fastest.
0

Commented:
A table lookup will work for all the numbers if the table is correctly set up for all the numbers.
0

Commented:
Thatis, if you mean by "all the numbers" all 8bit types. For larger types, the lookup table becomes impractical, and you should favor ozo's second solution (with a few minor changes to account for the increased size).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.