给定一个二进制补码形式的字节,我试图将该字节转换为它的十进制表示形式。例如 byte
10000000
我需要转换为 -128
和 byte
01111111
我需要转换为 127
。我看过这个answer ,但我没有成功地采用其中一个答案并使其对我有用。
我该如何进行转换?
澄清:我正在尝试将二进制补码形式的 byte
转换为 int
而不是二进制值的 string
表示进入一个`int。
最佳答案
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;
}
关于c# - 如何将二进制补码形式的字节转换为其整数值? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48567214/