# Delphi——从Integer到Byte类型（负数转换）

[英]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 ).我希望在数字 10 中的变量中看到结果（因为这是 integer 类型的低字节）。 But the result was B => 246.但结果是 B => 246。

Logically, I understand that 246 = 256 - 10, but I can't understand why this happened?从逻辑上讲，我理解 246 = 256 - 10，但我不明白为什么会这样？

Your expectation of the value 10 for the least significant (ls) byte of the integer with value -10 is not correct.对于值为 -10 的 integer 的最低有效 (ls) 字节，您期望值为 10 是不正确的。

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.负数根据称为2's complement的系统进行编码，其中值 -1 作为四字节 integer 编码为 \$FFFFFFFF，-2 编码为 \$FFFFFFFE，-3 编码为 \$FFFFFFFD... -10 编码为 \$FFFFFFFF6...等等。 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).您可能想到的是一个称为Signed magnitude的系统（请参阅： https://en.wikipedia.org/wiki/Signed_number_representations ），其中最高有效位在设置时表示负值，而实际数字的编码位置对于负数和正数都相同（定义两个零值 +0 和 -0 会带来不便）。

The value `-10` is `\$FFFFFFF6` in an `Integer` .`-10`是 Integer 中的`\$FFFFFFF6` `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` .将其分配给宽度较小的类型只会截断该值 - 这意味着`B`中的值将是`\$F6` ，即`246`

If you compile with range checking you will get an exception because `-10` does not fit into a `Byte` .如果您使用范围检查进行编译，您将得到一个异常，因为`-10`不适合`Byte`

If you want to turn a negative number into a positive you need to use the Abs function.如果你想把一个负数变成一个正数，你需要使用Abs function。