i have question on this topic i think that answer is incorrect look
http://stackoverflow.com/questions/1192487/swap-bits-in-a-number-in-c
1110 1011 it is equal 235 but i get 3051 why?
i have question on this topic i think that answer is incorrect look
http://stackoverflow.com/questions/1192487/swap-bits-in-a-number-in-c
1110 1011 it is equal 235 but i get 3051 why?
Most likely you do have the correct number, but you are using %d
to print it without casting it to an int (or something else funny in the way you display it).
I say this because (3051 & 235) == 235
, which is an unlikely coincidence to happen randomly.
You've shown only 8 bits, which means the maximum possible value is 28-1, which works out to 255.
3051 in binary is: 1011 1110 1011, so to get that, you've apparently duplicated the least significant nybble into the third nybble.
The value 3051
in decimal is 101111101011
in binary. If you split it up into four bit segmens like this: 1011 1110 1011
, you see that the lowest four bits are repeated above the eight bits that you want. The reason for that is that you haven't masked the value that should be the top four bits.
So instead of something like this:
(c >> 4) | ((c & 0x0f) << 4)
or something like this:
((c >> 4) | (c << 4)) & 0xff
you simply have this:
(c >> 4) | (c << 4)