I'm confused about WHERE the shifting begins. For instance let's say we have a problem like . That bit representation would be . My question is where do I begin shifting the bits? At the 1 or at the 0 following the 1? Is it or ?

For right-shifting you would shift the bits beginning from the right side (right-most). ex. 1111 1111 1110 1000, begin by shifting the 0's.

Originally posted by Jay Dilla: I'm confused about WHERE the shifting begins. For instance let's say we have a problem like . That bit representation would be . My question is where do I begin shifting the bits? At the 1 or at the 0 following the 1? Is it or ?

Jay, bit shifting works like this: To shift a number one bit to the right, remove the rightmost bit and add a bit on the left. If the leftmost bit before the shift is 0, add a 0; if it is 1, add a 1.

So looking at your example 32 >> 3:

32 == 0010 0000

Shift this to the right three times, using the method described above. This gives:

0001 0000 0000 1000 0000 0100

So the answer is 0000 0100 == 4.

Note, you always have to take all the bits in the number into account. If your are shifting an int, which is 32 bits, you should look at all 32 bits:

0000 0000 0000 0000 0000 0000 0010 0000 [ August 30, 2007: Message edited by: Jesper Young ]

Jay Dilla
Ranch Hand

Joined: Aug 12, 2004
Posts: 199

posted

0

Why should I be concerned with ALL bits? Shouldn't I only care about the bit immediately in front of my starting point?

Originally posted by Jay Dilla: Why should I be concerned with ALL bits? Shouldn't I only care about the bit immediately in front of my starting point?

if you are dealing with only positive numbers, it doesn't matter too much. but if your intial value is negative, it will matter. say i have

1001 0000

doing a right shift would give me

1100 1000

but if i'm using an int, I may have this:

1000 0000 0000 0000 0000 0000 0010 0000

and shift it one, i'd have this:

1100 0000 0000 0000 0000 0000 0001 0000

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Originally posted by Jay Dilla: Why should I be concerned with ALL bits? Shouldn't I only care about the bit immediately in front of my starting point?