问题
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 );
then inverting it, but i couldn't use the NOT
operator.
is there any short way to invert the bits and then adding 1 (2's complement operation)?
回答1:
The answer might depend on whether or not the bit width of the value is important to you.
The short answer is:
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"
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"
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.
回答2:
Two complment is really simple:
int value = 100;
value = ~value // NOT
value = value + 1;
//Now value is -100
Remember that a two complement system requires inverting and adding plus 1.
In hex:
int value = 0x45;
value = ~value // NOT
value = value + 1;
来源:https://stackoverflow.com/questions/14929072/expressing-hex-value-in-2s-complement