Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressing hex value in 2's complement

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)?

like image 671
Liban Avatar asked Feb 18 '13 03:02

Liban


1 Answers

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.

like image 127
Corey Avatar answered Sep 28 '22 05:09

Corey