0

I'm having trouble converting a Decimal to its Hex signed 2's complement. I use this site to check if my conversions are correct but none seems to be working.

Example:

0002159721(Decimal) when converted to Hex signed 2's complement should be 0020F469

I was able to convert the decimal to hex using this code.

string dec = "0002159721";
string hex = Convert.ToUInt32(dec).ToString("X"); //result: 20F469

Now, I'm having trouble to get the 2's complement. This is what I have so far.

uint intVal = Convert.ToUInt32(dec, 16);
uint twosComp = ~intVal + 1;
string h = string.Format("{0:X}", twosComp);
string h1 = twosComp.ToString("X"); // result: FFDF0B97

Here's the result from rapid tables site: enter image description here

Kate Lastimosa
  • 169
  • 2
  • 15
  • 1
    Does this answer your question? [expressing hex value in 2's complement](https://stackoverflow.com/questions/14929072/expressing-hex-value-in-2s-complement) – Self Apr 12 '21 at 09:27
  • I tried that as well but still gives me the same result which is FFDF0B97 – Kate Lastimosa Apr 12 '21 at 09:31
  • FFDF0B97 is correct? That's -2159721, expressed in 2's complement hex – canton7 Apr 12 '21 at 09:32
  • I'm expecting the Hex signed 2's complement result to be 0020F469 for the decimal 0002159721. I use this site to check the values. https://www.rapidtables.com/convert/number/decimal-to-hex.html – Kate Lastimosa Apr 12 '21 at 09:38
  • https://stackoverflow.com/questions/15919979/convert-int-to-hex-with-leading-zeros/15920036 – Magpie Apr 12 '21 at 09:45
  • I think you're confused. For positive signed integers, the signed 2's complement bit representation of a number is the same as for unsigned integers. 2159721 in decimal is represented as 20F469 in hex, both as an unsigned number, and as a signed 2's complement number – canton7 Apr 12 '21 at 09:46
  • That's clearly wrong FFDF0B97 is the correct result. A negative number always has the top bit set. – PMF Apr 12 '21 at 09:46
  • FFDF0B97 is -2159721 in 2's complement, note the negative sign. 2159721 (the positive value) is 20F469, both as an unsigned int, and as a 2's complement signed int – canton7 Apr 12 '21 at 09:47
  • So the problem is that the value you're getting is missing the leading `00`? – canton7 Apr 12 '21 at 10:14
  • Yes. I need the result to have the leading `00` like on the photo. Is there a way to get that same result? – Kate Lastimosa Apr 12 '21 at 10:43
  • Use `.ToString("X8")` to tell it to pad it out to 8 characters, using leading zeros if necessary – canton7 Apr 12 '21 at 10:51
  • Note that your website just arbitrarily decided to pad the output to 8 characters -- that's nothing to do with 2's complement – canton7 Apr 12 '21 at 10:53

0 Answers0