C#字节数组-有符号和无符号难题 [英] C# byte arrays - signed and unsigned dilemma

查看:92
本文介绍了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

这篇关于C#字节数组-有符号和无符号难题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆