Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - from Integer to Byte type (negative number conversion)

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?

like image 761
DevSergo Avatar asked Sep 15 '25 05:09

DevSergo


1 Answers

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).

like image 134
Tom Brunberg Avatar answered Sep 17 '25 02:09

Tom Brunberg