c# - 用 2 的补码表示十六进制值

标签 c# bit-manipulation

我有一个字符串的十六进制值,我需要用 2 的补码表示它。

string hx = "FF00";

我所做的是,将其转换为二进制:

 string h = Convert.ToString(Convert.ToInt32(hx, 16), 2 );

然后反转它,但我不能使用 NOT 运算符。

有没有简单的方法来反转位然后加 1(2 的补码运算)?

最佳答案

答案可能取决于值的位宽对您是否重要。

简短的回答是:

string hx = "FF00";
uint intVal = Convert.ToUInt32(hx, 16);      // intVal == 65280
uint twosComp = ~v + 1;                      // twosComp == 4294902016
string h = string.Format("{0:X}", twosComp); // h == "FFFF0100"

h 的值是“FFFF0100”,它是 hx 的 32 位 2 的补码。如果您期望“100”,那么您需要使用 16 位计算:

string hx = "FF00";
ushort intVal = Convert.ToUInt16(hx, 16);    // intVal = 65280
ushort twosComp = (ushort)(~v + 1);          // twosComp = 256
string h = string.Format("{0:X}", twosComp); // h = "100"

请记住,uintUInt32 的别名,ushortUInt16 类型的别名。为了清楚地了解此类操作,您最好使用显式名称。

关于c# - 用 2 的补码表示十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14929072/

相关文章:

c# - 发送FIN包,通知数据已发送

c# - Linq Where 语句性能缓慢

c# - 为什么在通过泛型方法创建时在本地评估 Select 之后的 Linq "where"表达式?

c - 内存块中的位重置

mysql - 设置 Int16 溢出时的累加值

algorithm - Q : Count array pairs with bitwise AND > k ~ better than O(N^2) possible?

c# - ASP.NET MVC - HTML.BeginForm 和 SSL

c# - WPF 中的 DispatcherPriority

c++ - (n & m) <= m 总是正确的吗?

c - 带符号类型的移位运算符