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:
The value of
his 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:Bear in mind that
uintis an alias forUInt32andushortaliases theUInt16type. For clarity in this type of operation you’d probably be better off using the explicit names.