RE: bit shifting doesn't work as expected

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> I have the following small programm, and I don't understand why the
> number is feeded with ones from the right, but not with
> zeros.

To elaborate a bit on the other response : this is usually called
"sign extended shift right". It preserves the sign of a signed
integer, which is stored in the top bit (0 = +ve, 1 = -ve).

If you have 2 signed integers, a, and b, such that a = -b, then shift
them both x bits right, then it will still be true that a = -b.

If the sign bit is not preserved, -ve numbers change into very large
+ve numbers after a shift right. For example, for 16 bit signed
integers:
 non sign extended: 11000000 (-64) >>2  ==>  00110000 (48)
 sign extended:     11000000 (-64) >>2  ==>  11110000 (-16)

The first one is correct if the numbers are UNSIGNED, and the first
represents +192 rather than -64.

> And the next question would be: How can I manage it to get zeros,
> instead of ones?

As suggested, use unsigned data types.

HTH

--
Matthew JONES
http://www.tandbergtv.com/


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux