Bit shift and pointer oddities in C, looking for explanations

Posted by foo on Stack Overflow See other posts from Stack Overflow or by foo
Published on 2010-05-16T18:00:28Z Indexed on 2010/05/16 18:10 UTC
Read the original article Hit count: 347

Filed under:
|
|

Hi all, I discovered something odd that I can't explain. If someone here can see what or why this is happening I'd like to know. What I'm doing is taking an unsigned short containing 12 bits aligned high like this:

1111 1111 1111 0000

I then want to shif the bits so that each byte in the short hold 7bits with the MSB as a pad. The result on what's presented above should look like this:

0111 1111 0111 1100

What I have done is this:

unsigned short buf = 0xfff;
//align high
buf <<= 4;

buf >>= 1;
*((char*)&buf) >>= 1;

This gives me something like looks like it's correct but the result of the last shift leaves the bit set like this:

0111 1111 1111 1100

Very odd. If I use an unsigned char as a temporary storage and shift that then it works, like this:

unsigned short buf = 0xfff;
buf <<= 4;

buf >>= 1;
tmp = *((char*)&buf);
*((char*)&buf) = tmp >> 1;

The result of this is:

0111 1111 0111 1100

Any ideas what is going on here?

© Stack Overflow or respective owner

Related posts about c

    Related posts about bit-shift