Reputation: 59
I am new to Swift, and I am reading The Big Nerd Ranch Guide. I came across this example:
He wants me to get the value of z
let y: Int8 = 120
let z = y &+ 10
print ("120 &+ 10 is \(z)")
He mentioned that the result of overflow-adding 120 + 10 and storing the result into an Int8 is -126
I don't understand the logic of this result. I tried to read more resources about the overflow operators, but I got more confused. I'd greatly appreciate your help.
Upvotes: 1
Views: 627
Reputation: 23701
In binary, the value of y, 120 is:
01111000
If you add 10 to that (which is 1010 in binary) you get:
10000010
If you take that binary pattern and interpret it as a signed 8 bit integer, you note that the high bit is 1 (which means the number is negative) and the value of the negative number is the twos complement of the pattern (0000010) which is (1111101 + 1) or (1111110) which is 126
Therefore the result is -126
Upvotes: 2