Reputation: 179
Can anybody tell me why the output is not -1 but 18446744073709551615?
package main
import (
"fmt"
)
func main() {
a := uint(0)
b := uint(1)
fmt.Println(a - b)
}
output
18446744073709551615
currently, my understanding is the following.
subtraction in pc will be converted into addition. And b is minus, so the 2's complement of a(0) and b(-1) will be used in addition.
so the calculation is like
00000000 00000000 00000000 00000001 <- 2's complement of 0
11111111 11111111 11111111 11111110 <- 2's complement of -1
11111111 11111111 11111111 11111111 <- 2's complement of (result: 0 + -1)
Usually, if a and b is a type of int, 2's complement will be converted to binary result(10000000 00000000 00000000 00000001) which is -1 automatically. But a and b is the type of unit, so the convert into binary will not be taken, it will treat the result of 11111111 11111111 11111111 11111111(2's complement) as a normal binary result and output it. ← Does this explanation correct?
Does my understanding miss something?
Another question is that 11111111 11111111 11111111 11111111 should be pow(2,64) - 1 which is 18446744073709552000
Why my output is only 18446744073709551615?
Upvotes: -3
Views: 1058
Reputation: 691
And just to answer the "another question":
... should be pow(2,64) - 1 which is 18446744073709552000
Why my output is only 18446744073709551615?
264 - 1 is 18446744073709551615.
If you're getting 18446744073709552000, my guess would be you're getting it from a calculator that uses a decimal floating-point representation and not enough digits of precision to represent it exactly.
(Standard binary floating point formats would have 18446744073709551616 as the nearest representable answer.)
Aside: 264 - 1 could not possibly be equal to 18446744073709552000, because powers of two are even numbers for obvious reasons, so 2N - 1 must be odd.
Upvotes: 1
Reputation: 5395
uint64 is the set of all unsigned 64-bit integers. Range: 0 through 18446744073709551615.
Upvotes: 1