c# - 如何将十六进制字符串转换为有符号整数?

标签 c# .net integer hex signed

我得到一个十六进制字符串,需要将其转换为带符号的 8 位整数。目前我正在使用 Int16/Int32 进行转换,这显然不会给我一个 8 位整数的负值。如果我得到十六进制值 255,如何将其转换为十进制 -1?我假设我想使用 sbyte,但我不确定如何正确地获取该值。

最佳答案

您可以使用 Convert.ToSByte

例如:

string x = "aa";
sbyte v = Convert.ToSByte(x, 16);
// result: v = 0xAA or -86

您还可以使用 sbyte.Parse

例如:

string y = "bb";
sbyte w = sbyte.Parse(y, System.Globalization.NumberStyles.HexNumber);
// result: w = 0xBB or -69

要回答有关 Int16 的高字节或低字节的问题:

string signed_short = "feff";

// Truncate 16 bit value down to 8 bit
sbyte b1 = (sbyte)Convert.ToInt16(signed_short, 16);
sbyte b2 = (sbyte)short.Parse(signed_short, System.Globalization.NumberStyles.HexNumber);
// result: b1 = 0xFF or -1
// result: b2 = 0xFF or -1

// Use upper 8 bit of 16 bit
sbyte b3 = (sbyte)(Convert.ToInt16(signed_short, 16) >> 8);
sbyte b4 = (sbyte)(short.Parse(signed_short, System.Globalization.NumberStyles.HexNumber) >> 8);
// result: b3 = 0xFE or -2
// result: b4 = 0xFE or -2

关于c# - 如何将十六进制字符串转换为有符号整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705429/

相关文章:

c# - 以编程方式安装 APK Xamarin.Forms (Android)

ruby - 12345.class 在 Ruby 中返回 'Integer' 而不是 'Fixnum'

javascript - Visual Studio 2012 中的 '/' 应用程序中的 ASP.NET 服务器错误

c# - 我需要一些关于命中计数器算法的想法(按时间间隔分组)

c# - 如何在不同线程中同时使用队列

c# - 什么时候在 .net 中使用预处理器指令?

.net - WCF - 客户端代理配置与服务 web.config 不匹配

bash - 使用 SED 或 AWK 获取 RHEL 版本的一位整数

java - 获取不断变化的整数的值

c# - 使用数值对字符串列表进行排序