Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do some hex numbers have a 2s compliment but some do not?

I want to write out the 2s compliment of the hex 0x1234

As I understand the binary would look like: 0001 0010 0011 0100 and decimal 4660

I was under the impression changing the leading 0 indicates positive vs negative, however online calculators aren’t giving me any answer so my understanding of this is wrong

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Alternatively looking at 0x8001 as an example: the decimal would be 32769 and the binary 1000 0000 0000 0001

Online calculators return an answer of -32767 as the 2s compliment

Could anyone please offer an explanation or some other post that explains in detail this concept of 2s compliment? Thank you very much!

>Solution :

You get a number’s two’s complement by inverting all bits and then adding one to it. It must be agreed up front how many bits/digits are involved, i.e. what the word size is. For instance, the result will not be the same for 0x1234 and 0x00001234.

For your example (4 hex digits): 0x1234

In binary: 0b0001 0010 0011 0100

Invert bits: 0b1110 1101 1100 1011

Add one: 0b1110 1101 1100 1100

In hex: 0xEDCC

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading