Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Suppose you have the bit pattern 0xFE and you add 0x1 to it, producing 0xFF. If you interpret that operation as signed math it's computing 254 + 1 = 255, while if you interpret it as unsigned math it was -2 + 1 = -1.

Isn't that backwards? The first one is unsigned, the second one is signed.



Actually they are neither signed nor unsigned, but modular numbers, modulo 256.

Any number modulo 256 is a representative for an infinity of integer numbers, e.g. 0xff stands for ... -257, -1, 255, 511, ... and 0x01 stands for ... -255, +1, 257, 513, ... and 0xfe stands for ... -258, -2, 254, 510, ... and 0x80 stands for ... -384, -128, +128, 384, ...

In hardware, the operations with modular numbers are implemented first, and then, in addition to them, a few Boolean functions are added, to allow the interpretation of the modular number operations as signed integer operations and/or unsigned integer operations. For the former overflow and sign are needed, while for the latter carry/borrow is needed.

Besides comparison of non-equal numbers, the most important operation that is meaningless for modular numbers, so it is defined only for signed or unsigned operands, is extension from a binary format with less bits to a format with more bits, a.k.a. sign extension for signed operands and zero extension for unsigned operands. Comparison and extension depend on overflow, sign and carry.

So normally, when attempting to understand a sequence of operations on binary numbers, they should be performed as modular operations and only the final result should be interpreted as desired, e.g. as signed or unsigned.

(For efficiency reasons, the actual implementation of two's complement multiplication and division with double-length product or dividend is a little more complex than this, because they correspond with double-length modular operations, but instead of that they are implemented by distinct algorithms operating on single-length numbers. When trying to verify such operations, it is still possible to compute them as double-length modular operations, if correct conversions are used, i.e. with sign extension)


> and only the final result should be interpreted as desired, e.g. as signed or unsigned.

Yes, and that's the latter half of what I quoted. The part that looks backwards, where it's using the labels "signed" and "unsigned".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: