简体   繁体   English

C#字节数组-有符号和无符号困境

[英]C# byte arrays - signed and unsigned dilemma

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

And the print (I just append them with a StringBuilder): 和打印(我只是将它们附加一个StringBuilder):

signed: [10,100,120,-76,-56,-36,-16] 签名:[10,100,120,-76,-56,-36,-16]
unsigned : [10,100,120,180,200,220,240] 未签名:[10,100,120,180,200,220,240]

where: 哪里:

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;

Shouldn't -128 (signed) become 0, -118 become 10, and so on.. and not 10 (signed) = 10 (unsigned)!? -128(带符号)不应该变成0,-118(带符号)不应该变成10,依此类推..而不是10(带符号)= 10(无符号)!

Because 因为
sbyte -128 to 127 字节-128至127
byte 0 to 255 字节0至255

So?? 所以??

Signed integers are represented in the Two's complement system . 有符号整数在二进制补码系统中表示

Examples: 例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM