• C

# Bitwise Shift in C and Arithmetic Shift

If x is a singed char.  Does x >> n still the same as the integer division of 2^n and x << n same as the multiplication of 2^n?

Why does it work/not work?

How does arithmetic shift work?
Let's say if I have a signed char of 1001 in binary, -1 in decimal.
With an arithmetic right shift by 1 become 1100?  Would it means -4 in decimal?  so the multiplication we mentioned above won't work even for arithmetic shift.

Thanks!
###### Who is Participating?

Commented:
Signed chars are typically "two's complement", so the binary 8-bit value 10000001 is NOT -1.  -1 is represented by 11111111.

A series of "arithmetic right shifts" of positive numbers will eventually yield a result of 0 (00000000), whereas the same series of shifts on a negative result will eventually give the result of -1 (11111111).  In other words, division by shifting  right results in 'rounding down' on an absolute basis for positive values, and 'rounding up' on an absolute basis for negative values.

Some examples to show that right shifts work as division for negative numbers:

-16 / 2 = -8       11110000 >> 2 = 11111000 = -8

-59 / 16 = -4      11000101 >> 5 = 11111100 = -4
(Note the rounding up)

Hope this helps.
0

Commented:
8 bit signed char
x = 10000001 in binary, -1 in decimal.
x << 1 = 00000010 = 2 in decimal
x >> 1 = 01000000 = 64 in decimal

So yeah, they don't work for negative number.
For positive number, they work

y = 00010000 in binary, 16 in decimal.
y << 1 = 00100000 = 32 in decimal
y >> 1 = 00001000 = 16 in decimal

until ...
y << 4 = 1000000 = ... you know how many it is, don't you

0

Commented:

You're right honey_hamster, but you're shifting by 1 too many in your examples.

/2  --->  >> 1
/16  --->  >> 4

--tri
0

Commented:
Thanks TriG - I shifted the binary number the correct number, but for some reason I put the wrong number after the ">>".  Oops.
0

OwnerCommented:
Nothing has happened on this question in more than 9 months. It's time for cleanup!

My recommendation, which I will post in the Cleanup topic area, is to

jmcg
EE Cleanup Volunteer
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.