468,512 Members | 1,423 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

Rotational bitwise shift

As I understand it, the unsigned long type is 4 bytes. Also, the bitwise shift (<<) is a zero-fill shift as opposed to a rotational shift. However when I shift, the value seems to be rotating, as opposed to being lost as I would expect.

Anybody have any ideas?


Expand|Select|Wrap|Line Numbers
  1. char resBuffer[sizeof(unsigned long)];
  2.  
  3. unsigned long value=1;
  4.  
  5. memcpy(resBuffer, &value, sizeof(unsigned long));
  6.  
  7.  
  8.  
Leaves resBuffer = { 1, 0, 0, 0 } as I would expect.


Expand|Select|Wrap|Line Numbers
  1. char resBuffer[sizeof(unsigned long)];
  2.  
  3. unsigned long value=1;
  4.  
  5. value = (value << 8);
  6.  
  7. memcpy(resBuffer, &value, sizeof(unsigned long));
  8.  
  9.  
  10.  
Leaves resBuffer = { 0, 1, 0, 0 } as I would expect.


Expand|Select|Wrap|Line Numbers
  1. char resBuffer[sizeof(unsigned long)];
  2.  
  3. unsigned long value=1;
  4.  
  5. value = (value << 36);
  6.  
  7. memcpy(resBuffer, &value, sizeof(unsigned long));
  8.  
  9.  
  10.  
However, leaves resBuffer = { 16, 0, 0, 0 }

Why isn't the result { 0, 0, 0, 0 } as I would expect?

Thanks for taking the time to read through this!
Oct 10 '06 #1
1 6393
Banfa
9,056 Expert Mod 8TB
I believe you may be running into undefined behaviour (I just can't actually find anyway that categorically states it) with

value = (value << 36);

because you are shifting more bits than is in an unsigned long (32) in this case.

If this is the case then having invoked undefined behaviour the compiler is free to do whatever it wants, on my system it looks like what it does is shift by (shift % 32), for 36 this results in a left shift by 4.

Anyway you should not rely on undefined behaviour because (being undefined) it can change by platform, compiler or even compiler version.
Oct 11 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

11 posts views Thread by Randell D. | last post: by
3 posts views Thread by sandy_pt_in | last post: by
8 posts views Thread by Paul E Collins | last post: by
8 posts views Thread by Rudolf | last post: by
4 posts views Thread by kernelxu | last post: by
1 post views Thread by PengYu.UT | last post: by
5 posts views Thread by noridotjabi | last post: by
5 posts views Thread by Gigs_ | last post: by
5 posts views Thread by Rahul | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.