#18237 - ScottLininger - Mon Mar 22, 2004 11:28 pm
Can anyone tell me why
x = (x << 8) >>8;
yields a different value than
x = (x * 256) >> 8;
???
x is a u16. I've seen this bug 2 or 3 times, so I'm ready to give up on left bitshifts and stick with multiplication. Am I just totally missing something?
In the example above, I'm trying to grab the bottom 8 bits out of a u16.
#18238 - ScottLininger - Mon Mar 22, 2004 11:32 pm
No wait, that's not what I really want to ask. What I really want to ask is, why is:
x = x << 8;
x = x >> 8;
a different value than...
x= (x<<8)>>8
Is the stack a u32 or something?
#18239 - ScottLininger - Mon Mar 22, 2004 11:39 pm
As a side note, is multiplication slower than bitshifting?
#18240 - yaustar - Mon Mar 22, 2004 11:56 pm
yes, multipication is slower then bitshifting
As for the bug, I get no problems with it
Code: |
#include <stdio.h>
#include <stdlib.h>
typedef unsigned short u16;
#define number 230
int main(void)
{
u16 x = number;
printf("%d\n", x); // 230
x = x << 8;
x = x >> 8;
printf("%d\n", x); // 230
x = number;
printf("%d\n", x); // 230
x = (x << 8) >> 8;
printf("%d\n", x); // 230
system("pause");
} |
edit: if you want to grab the last 8 bits then try masking
_________________
[Blog] [Portfolio]
#18243 - tepples - Tue Mar 23, 2004 12:53 am
ScottLininger wrote: |
why is:
Code: | x = x << 8;
x = x >> 8; |
a different value than...
Is the stack a u32 or something? |
ANSI C specifies that intermediate results of most operators, including << and >>, are in fact expanded to (signed int) or (unsigned int) as appropriate.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.