Home > Software engineering >  Delphi - from Integer to Byte type (negative number conversion)
Delphi - from Integer to Byte type (negative number conversion)

Time:01-24

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?

CodePudding user response:

The value -10 is $FFFFFFF6 in an Integer. Assigning that to a lower-width type will simply truncate the value - that means the value in B will be $F6 and that is 246.

If you compile with range checking you will get an exception because -10 does not fit into a Byte.

If you want to turn a negative number into a positive you need to use the Abs function.

CodePudding user response:

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

  • Related