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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With