How do computers represent negative numbers anyway?
Over the years, several methods have been designed to represent negative numbers, but in order to keep this answer on the short side of the dissertation, we will consider only two additions. one
To calculate the complement with a negative number two, we use the following steps:
- Take the value of the number (this is the absolute value)
- Complete all bits (bitwise)
- Add 1 to the result (simple add)
So, what is -8 in two binary additions? First let me convert the absolute value to binary (now we will work in 8 bits for simplicity. I developed the same answer below with 32-bit numbers.)
|8| => 0000 1000
The next step is to complete all bits of the number
0000 1000 => 1111 0111
Finally, we add 1 to the result to get our view with two additions.
1111 0111 + 1 ---------- 1111 1000 (Don't forget to carry)
Well, a brief overview of octal numbers. Octal or base 8 is another way to represent binary numbers in a more compact way. More observant noted that 8 is the power of 2, and we can certainly use this fact in our interests, turning our negative number into octal.
Why does this make Oct produce strange results with negative numbers?
The Oct function works on the binary representation of a number, converting it to an octal representation (Base 8). So let me convert our 8-bit number to octal.
1111 1000 => 11 111 000 => 011 111 000 => 370
Note that since 8 = 2^3 easy to convert, because all we need to do is split the number into groups of three bits and convert each group. (How and how hex can be converted by splitting into groups of 4 bits.)
So, how do I get Oct to get a regular result?
Convert the absolute value of a number to octal using Oct If the number is less than 0, put a negative sign in front.
Example of using 32-bit numbers
We will stay with -8 because it has been so good for us all this time. Therefore, converting -8 to two additions gives:
Convert: 0000 0000 0000 0000 0000 0000 0000 1000 Invert: 1111 1111 1111 1111 1111 1111 1111 0111 Add 1: 1111 1111 1111 1111 1111 1111 1111 1000 Separate: 11 111 111 111 111 111 111 111 111 111 000 Pad: 011 111 111 111 111 111 111 111 111 111 000 Convert: 3 7 7 7 7 7 7 7 7 7 0 Shorten: 37777777770
Which gives the result that you see when calling Oct(-8) .
Armed with this knowledge, you can also explain why Hex(-8) creates 0xFFFFFFF8 . (And you can understand why I used 8-bit numbers for most of this.)
1 For too detailed introduction to binary numbers, see Wikipedia article