C#字节数组-有符号和无符号难题
我从一个有符号字节数组开始,然后转换为无符号..那么打印结果是否正确?
I start with a signed byte array and convert to unsigned.. so is the printed result correct?
byte[] unsigned = new byte[] {10,100,120,180,200,220,240};
sbyte[] signed = Utils.toSignedByteArray(unsigned);
打印(我只是在它们后面加上StringBuilder):
And the print (I just append them with a StringBuilder):
签名:[10,100,120,-76,-56,-36,-16]
未签名:[10,100,120,180,200,220,240]
signed: [10,100,120,-76,-56,-36,-16]
unsigned : [10,100,120,180,200,220,240]
其中:
public static sbyte[] toSignedByteArray(byte[] unsigned){
sbyte[] signed = new sbyte[unsigned.Length];
Buffer.BlockCopy(unsigned, 0, signed, 0, unsigned.Length);
return signed;
}
如果我更改为该参数,则会得到相同的结果。
If I change to this I get the same result.
sbyte[] signed = (sbyte[])(Array)unsigned;
不应使-128(带符号)变为0,-118变为10,依此类推。而不是10(有符号)= 10(无符号)!?
Shouldn't -128 (signed) become 0, -118 become 10, and so on.. and not 10 (signed) = 10 (unsigned)!?
因为
sbyte -128到127
字节0到255
Because
sbyte -128 to 127
byte 0 to 255
所以??
带符号的整数在二进制补码系统中表示。
Signed integers are represented in the Two's complement system.
示例:
Bits Unsigned 2's complement
value value
00000000 0 0
00000001 1 1
00000010 2 2
01111110 126 126
01111111 127 127
10000000 128 −128
10000001 129 −127
10000010 130 −126
11111110 254 −2
11111111 255 −1