JQLT3E
asked on
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!
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!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You're right honey_hamster, but you're shifting by 1 too many in your examples.
/2 ---> >> 1
/16 ---> >> 4
--tri
Thanks TriG - I shifted the binary number the correct number, but for some reason I put the wrong number after the ">>". Oops.
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
accept answer by honey_hamster.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
jmcg
EE Cleanup Volunteer
My recommendation, which I will post in the Cleanup topic area, is to
accept answer by honey_hamster.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
jmcg
EE Cleanup Volunteer
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