Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How does the cpu work out greater than (>) in unsigned ints?

  1. Mar 25, 2015 #1
    Hey all, I understand how the cpu does most things but I can't figure out how it would work out greater than or less than in unsigned integers, in signed you could simply subtract them and check the highest bit for sign (I assume) but unsigned ints will loop back to the greatest value if A-B where B>A, any help apreciated.
  2. jcsd
  3. Mar 25, 2015 #2


    User Avatar

    Staff: Mentor

    You just do the subtraction with one extra zero bit on the left side of the operands. If you're comparing 64 bit integers, the operation is done in a 65-bit register. (In practice, the CPU designer doesn't mess with constructing actual 65-bit registers and data paths, we just do the subtraction in 64 bits and check for a carry out of the leftmost bit).
    Last edited: Mar 25, 2015
  4. Mar 25, 2015 #3
    Thank you so much! Can't believe I didn't think of that *facepalm*
  5. Mar 25, 2015 #4
    To Expand a bit on what Nuqatory said its all in the operation of the ALU
    When the ALU performs an operation, in this case a subtraction, a number of bits may get set in the Program Status Word.
    For example
    N: Result was negative
    Z: Result was Zero
    C: Result had a carry out

    So if you did a piece of code
    Code (Text):

    if(a>b) then
       do something
      do something else
    the CPU would undertake the following actions
    Code (Text):

    Load a into Register1
    Load b into Register2
    Branch If N bit set to LABEL1
    Do something
    Branch to LABEL 2
    Do something else
    LABEL 2:
    hope that makes sense :)
  6. Mar 25, 2015 #5
    Of course the carry bit and not the N bit would be used for an unsigned comparision
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook