Search code examples
binarydecimaltwos-complementcomplementones-complement

What is wrong with my Ones Complement?


i want to do the following subtraction using ones complement Octal(24)-Hex(4B) and give a binary answer

Octal(24) is 20 decimal and Hex(4B) is 75 in decimal

20->10100 75->1001011

taking 1s complement of 75 0110100 and adding to 20

10100 +0110100 =1001000

adding the carry with the result 001000 + 1 =001001 which is wrong

Where am i going wrong ?

I am new here, sorry if any mistakes in the way its typed.


Solution

  • You have a small few mistakes in your version. let me show you a correct solution and then show you your mistake(s)

    We have the octal number 24 and the hex number 4B. both are fairly easy to translate to binary.

    every octal digit represents 3 binary digits.

     2   4 
    +++ +++
    010 100
    

    every hexadecimal digit represents 4 digits.

     4    B 
    ++++ ++++
    0100 1011
    

    now you build the complement:

    ~01001011
     ---------
     10110100
    

    the you need to add one. Otherwise you get 2 zeros. (+0 => 00000000, -0 => 11111111). this actually makes it a two's complement, but its needed unless you want weird results when crossing the 0-border

     10110100
    +00000001
    ---------
     10110101
    

    now your complement is done. Next step is to add both numbers

     00010100 #The Octal 24
    +10110101 #The complement
    ---------
     11001001
    

    The first digit is a 1 therefore its negative (as we'd expect since we did 20 - 75) Therefore we need to reverse it.

    First we subtract one: 11001000
    Then we invert it again: 00110111
    Which is decimal 55. Therefore 11001001 is decimal -55.
    20 - 75 = -55
    Voila, we are done :)

    First tiny note: you made a small mistake when converting 0x4B (= Hex 4B) into binary format. one digit is wrong :)

    Also, you forgot to add one. Then you did some weird stuff i don't get here:

    adding the carry with the result 001000 + 1 =001001 which is wrong

    Also, you didn't use fixed size numbers which made it impossible to you to find out if the result was negative. I sticked to 8 Bit here (except during octal -> binary conversion). (Keep in mind that with 8 bit your number range is from -127 to +128.) And in the end - as you couln't see its a negative number - you did not revert the process.

    I hope this explanation helped you out :)