在补前pressing十六进制值 [英] expressing hex value in 2's complement
问题描述
我有一个字符串十六进制值,我需要给前preSS它补。
i have a string hex value, and i need to express it in 2's complement.
string hx = "FF00";
我所做的是,将其转换为二进制的:
what i did is, converting it to binary:
string h = Convert.ToString(Convert.ToInt32(hx, 16), 2 );
然后翻转它,但我不能使用不是
运营商。
有反转位的一小段路,然后加入1(2的补操作)?
is there any short way to invert the bits and then adding 1 (2's complement operation)?
推荐答案
答案可能取决于是否不是值的位宽是对你很重要。
The answer might depend on whether or not the bit width of the value is important to you.
简短的回答是:
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,这是32位2的HX的补充。如果你期待'100',那么你需要使用16位的计算:
The value of h
is then "FFFF0100" which is the 32-bit 2's complement of hx. If you were expecting '100' then you need to use 16-bit calculations:
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"
请记住 UINT
是 UInt32的
一个别名, USHORT
别名 UINT16
键入。为了明确这种类型的操作你可能会更好用明确的名称。
Bear in mind that uint
is an alias for UInt32
and ushort
aliases the UInt16
type. For clarity in this type of operation you'd probably be better off using the explicit names.
这篇关于在补前pressing十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!