C Programmers In Here! Shifting Bits!

james182

Member
Jun 7, 2003
48
0
0
Lets say I have an int that I want to shift, always to the right, how can I shift that and fill the vacated bits with 0's?
 

james182

Member
Jun 7, 2003
48
0
0
yeah, that shifts the bits right but if there is a one in the far left position like this:
11001100 and I want to shift the bits two to the right it would end up looking like this:
11110011, I want it to look like this:
00110011.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Hm, I thought when things got shifted off the end, the "new" bits were zero.

You could & it with 00111111 afterwards. :p
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Originally posted by: james182
yeah, that shifts the bits right but if there is a one in the far left position like this:
11001100 and I want to shift the bits two to the right it would end up looking like this:
11110011, I want it to look like this:
00110011.

Cast it to an unsigned. Then, it will shift logically rather than arithmetically.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
When doing bit shifting, you should try to use unsigned ints in the first place.

How do you cast it to unsigned? I don't think we should tell you. :p Seriously though, that is a pretty rudimentary thing .. anandtech is not a replacement for a good education. ;)