left shift then right shift an unsigned int

W

Wenjie

Hello, for the following code:
unsigned int var = 0xFF2277F0UL;
unsigned char take2 = (var << 8) >> 24;
Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)


Thanks and best regards,
Wenjie
 
B

Bob Hairgrove

Hello, for the following code:
unsigned int var = 0xFF2277F0UL;
unsigned char take2 = (var << 8) >> 24;
Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)

It looks OK to me...
 
R

Ron Natalie

Greg Schmidt said:
As others have said, it looks fine, but it seems to me that
unsigned int var = 0xFF2277F0UL;
unsigned char take2 = (var >> 16) & 0xFF;
might be clearer as to the purpose, and easier to modify down the road.

I don't know what your assumptions are (since you hardcoded a lot of numbers
here), but if char is an 8 bit quantity, even the & 0xFF is superfluous.
 
R

Ron Samuel Klatchko

Hello, for the following code:
unsigned int var = 0xFF2277F0UL;
unsigned char take2 = (var << 8) >> 24;
Is there any pitfall about the shift? (get '22' i.e. 34 or '"' as wanted)

One pitfall is that it is dependent on the size of an unsigned int to
get the expected results. If unsigned int holds more then 32 bits,
the << 8 won't do the intended stripping.

Even worse, I think it isn't clear what this code is doing. I can
picture someone accidentally changing the code to:

var >> 16;

If I were writing the code, I'd making the stripping more explicit.

(var >> 16) & 0xFF

or possibly:

(var & 0xFF0000) >> 16

samuel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,829
Latest member
PIXThurman

Latest Threads

Top