views:

106

answers:

3

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?

+1  A: 

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.

Mark Rushakoff
Casting to `int` won't do any good -- 3051 will fit into an `int`. To do any good, you'd need to cast to `unsigned char` (and that's suspect -- code that produces 3051 where 235 is intended clearly needs to be fixed, not fudged around, at least IMO).
Jerry Coffin
A: 

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.

Jerry Coffin
+2  A: 

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)
Guffa