I tested some code:
var
B: Byte;
I: Integer;
begin
I := -10;
B := I;
end;
And I expected to see the result in the variable In the number 10 (since this is the low byte of the type integer ). But the result was B => 246.
Logically, I understand that 246 = 256 - 10, but I can't understand why this happened?
Your expectation of the value 10 for the least significant (ls) byte of the integer with value -10 is not correct.
Negative numbers are encoded according a system called 2's complement, where a value of -1 as a four byte integer is coded as $FFFFFFFF, -2 as $FFFFFFFE, -3 as $FFFFFFFD ... -10 as $FFFFFFF6 ... and so on. This is the system used by most computers/software at present time.
There are other systems too. The one you possibly thought of is a system called Signed magnitude (see: https://en.wikipedia.org/wiki/Signed_number_representations) where the most significant bit, when set, indicates negative values, and where the actual numbers are encoded the same for both negative and positive numbers (with the inconvenience of defining two zero values, +0 and -0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With