Understanding & identifying signed numbers

0

I'm new to this subject and I'm struggling to comprehend how 0xFFFFFFF & 0x00000001 can have the same sign, yet 0x0000001 and 0x12345678 have different signs. Based on my understanding thus far, hex digits that have the most significant bit between 0-7 are positive & 8-F are negative.

For further context, here is the thing I was trying to understand:

Question: Complete the C function that performs the operations and meets the requirements indicated in the comments.

Comments:

    /*
    * diffSign – return 1 if x and y have different signs 
    * Examples: diffSign(0xFFFFFFF, 0x00000001) = 0
    * diffSign(0x0000001, 0x12345678) = 1
    * Legal ops: & | ^ ~ << >>
    * 1-byte const (0x00 to 0xFF)
    */

Answer:

     int diffSign(int x, int y) {
        return ((x >> 31) & 0x1) ^ ((y >> 31) & 0x1);
    }

If possible, I would also greatly appreciate some clarification on how & 0x1 would help me to identify the sign! It seems rather redundant and I'm not too sure about the significance of that in the equation.

hex
bitwise-operators
integer-arithmetic
asked on Stack Overflow Jan 28, 2020 by Joanne Lim • edited Jan 28, 2020 by Joanne Lim

1 Answer

0

If you look closely, it makes perfect sense, just that you are not seeing that the most significant byte of 0xFFFFFFF is actually 0 because there are 7 F's.

0xFFFFFFF = 0x0FFF FFFF

which for a 32 bit integer represents a positive number.

However 0x0000001 and 0x12345678 do also have the same sign. Because what makes the difference is the most significant BIT. You are right that numbers with the most significant BYTE between 0-7 are positive, and 8-F negative. The comment in the function is wrong.

The code however is right, because it does 31 shifts to the right, leaving only the most significant BIT on each of the arguments (the sign bit of each argument) and does an XOR, which returns true only if both are not the same.

answered on Stack Overflow Jan 28, 2020 by payala • edited Jan 28, 2020 by payala

User contributions licensed under CC BY-SA 3.0