# Bit Shifting

Jay Dilla
Ranch Hand
Posts: 201
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 ?

rey leon
Greenhorn
Posts: 23
Dilla,

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 ?

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
leo r, please check your private messages for an important message from JavaRanch. You can see your private messages by clicking My Profile.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
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
Posts: 201
Why should I be concerned with ALL bits? Shouldn't I only care about the bit immediately in front of my starting point?

marc weber
Sheriff
Posts: 11343
Note that bit shifting is on the 1.4 exam, but not the 1.5 exam.

fred rosenberger
lowercase baba
Bartender
Posts: 12203
35
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

Brian Cole
Author
Ranch Hand
Posts: 908
1
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?

What starting point?

(n >> 3) is more or less equivalent to (n / 8).

In either case all the bits of n are operated on.