【问题标题】:How to convert a byte in two's complement form to it's integer value? C#如何将二进制补码形式的字节转换为整数值? C#
【发布时间】:2018-02-01 16:16:15
【问题描述】:

给定一个二进制补码形式的字节,我试图将该字节转换为它的十进制表示。例如byte 10000000 我需要转换为-128 和byte 01111111 我需要转换为127。我看过这个answer,但我没有成功地接受其中一个答案并让它对我有用。

如何进行转换?

澄清:我正在尝试将二进制补码形式的byte 转换为int,而不是将二进制值的string 表示转换为`int。

【问题讨论】:

  • 使用这个:int i = BitConverter.ToInt32(bytes, 0);其中 bytes 是您的字节数组:)
  • int value = (sbyte)byteval;
  • 11111111 在二进制补码中不是 -128。你确定这是正确的测试用例吗?您能否在问题中添加更多测试用例?
  • OP 对二进制补码编码的含义感到困惑。二进制补码中的 -128 是底数 2 中的 10000000。

标签: c#


【解决方案1】:
public static int ConvertTwosComplementByteToInteger(byte rawValue)
{
    // If a positive value, return it
    if ((rawValue & 0x80) == 0)
    {
        return rawValue;
    }

    // Otherwise perform the 2's complement math on the value
    return (byte)(~(rawValue - 0x01)) * -1;
}

【讨论】:

  • 抱歉,在我彻底检查之前我投了反对票。虽然它是正确的,但它有点复杂。如果您编辑答案,我将能够删除反对票。对不起
【解决方案2】:

您需要将其转换为 sbyte

byte b = 0b10000000;
sbyte s = (sbyte)b;

Console.WriteLine(s); // -128

您可以将其转换为 Int32 值并将其封装为

public static int ByteToInt32(byte value)
{
    return (sbyte)value;
}

【讨论】:

  • 对不起,我尝试了 OP 的示例。才发现不对
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 2016-07-16
  • 2021-10-04
  • 2015-04-19
  • 2020-02-26
  • 2016-08-31
相关资源
最近更新 更多