Expressing the hexadecimal value in 2 additions

I have a hexadecimal string value and I need to express it in 2 additions.

string hx = "FF00";

what i did was convert it to binary:

 string h = Convert.ToString(Convert.ToInt32(hx, 16), 2 );

then inverting it, but I could not use the operator NOT.

is there any short way to invert bits and then add 1 (2 padding operations)?

+5
source share
2 answers

The answer may depend on whether the value bit width is important to you.

Short answer:

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 his "FFFF0100", which is a 32-bit addition to hx. If you were expecting "100", you need to use 16-bit computing:

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. , , .

+4

:

int value = 100;

value = ~value // NOT
value = value + 1;

//Now value is -100

, 1.

:

int value = 0x45;

value = ~value // NOT
value = value + 1;
+3

All Articles