C# byte arrays - signed and unsigned dilemma

放肆的年华 提交于 2020-05-16 02:30:39

问题


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

signed: [10,100,120,-76,-56,-36,-16]
unsigned : [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)!?

Because
sbyte -128 to 127
byte 0 to 255

So??


回答1:


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


来源:https://stackoverflow.com/questions/10474186/c-sharp-byte-arrays-signed-and-unsigned-dilemma

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!