改进从十六进制读取有符号8位整数的方法
场景:
我有一串十六进制字符,它编码 8 位有符号整数。每两个字符代表一个字节,使用最左边的(MSB)位作为符号(而不是二进制补码)。我正在循环内将它们转换为有符号整数,并想知道是否有更好的方法来做到这一点。转换次数太多,我确信我缺少一种更有效的方法。
当前代码:
string strData = "FFC000407F"; // example input data, encodes: -127, -64, 0, 64, 127
int v;
for (int x = 0; x < strData.Length/2; x++)
{
v = HexToInt(strData.Substring(x * 2, 2));
Console.WriteLine(v); // do stuff with v
}
private int HexToInt(string _hexData)
{
string strBinary = Convert.ToString(Convert.ToInt32(_hexData, 16), 2).PadLeft(_hexData.Length * 4, '0');
int i = Convert.ToInt32(strBinary.Substring(1, 7), 2);
i = (strBinary.Substring(0, 1) == "0" ? i : -i);
return i;
}
问题:
是否有更简化和直接的方法来读取两个十六进制字符并将它们转换为 int(当它们表示有符号 int(-127 到 127)时)使用最左边的位作为符号?
Scenario:
I have a string of hexadecimal characters which encode 8-bit signed integers. Each two characters represent a byte which employ the leftmost (MSB) bit as the sign (rather than two's complement). I am converting these to signed ints within a loop and wondered if there's a better way to do it. There are too many conversions and I am sure there's a more efficient method that I am missing.
Current Code:
string strData = "FFC000407F"; // example input data, encodes: -127, -64, 0, 64, 127
int v;
for (int x = 0; x < strData.Length/2; x++)
{
v = HexToInt(strData.Substring(x * 2, 2));
Console.WriteLine(v); // do stuff with v
}
private int HexToInt(string _hexData)
{
string strBinary = Convert.ToString(Convert.ToInt32(_hexData, 16), 2).PadLeft(_hexData.Length * 4, '0');
int i = Convert.ToInt32(strBinary.Substring(1, 7), 2);
i = (strBinary.Substring(0, 1) == "0" ? i : -i);
return i;
}
Question:
Is there a more streamlined and direct approach to reading two hex characters and converting them to an int when they represent a signed int (-127 to 127) using the leftmost bit as the sign?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需将其转换为 int 并通过测试转换后的数字的大小并屏蔽符号位来处理符号位。
Just covert it to an int and handle the sign bit by testing the size of the converted number and masking off the sign bit.
像这样:(已测试)
解释:
unchecked
转换为sbyte
将执行直接转换为有符号字节,将最后一位解释为符号位。然而,它有不同的范围,所以它不会帮助你。
Like this: (Tested)
Explanation:
The
unchecked
cast tosbyte
will perform a direct cast to a signed byte, interpreting the final bit as a sign bit.However, it has a different range, so it won't help you.
然后:
Then: