Understanding Hexadecimal Printing Differences between Go and C: The Case of -1
In Go, the %x format for printing integers represents the value in hexadecimal notation. This is distinct from C's %x, which prints the memory representation of a signed integer. This difference leads to unexpected results when printing the negative integer -1.
In Go:
var x uint64 = 1 << 64 - 1 fmt.Printf("%x\n", x)
Output:
ffffffffffffffffffff
Here, %x correctly prints the hexadecimal representation of the unsigned value 1<<64 - 1.
In C:
#include <stdio.h> int main() { uint64_t x = 1LL << 64 - 1; printf("%x\n", (long long)x); }
Output:
-1
In C, %x prints the signed integer value -1, seemingly resulting in a negative hexadecimal number with a leading '-'. However, this is not the case; the '-' sign indicates that the integer is negative, and the hexadecimal value ffff...ff is the 2's complement representation of -1.
Go enforces strict typing, requiring explicit type conversions to treat signed integers as unsigned. To print -1 as an unsigned value in Go:
i := -1 // type int fmt.Printf("%x", uint(i))
Output:
ffffffff
This approach converts the signed integer -1 to its unsigned counterpart, resulting in the correct hexadecimal representation.
The default behavior of Go to print negative integers as signed values allows for concise representation, but it can lead to unexpected results in hexadecimal contexts. Understanding these differences is crucial for effective code writing in Go.
The above is the detailed content of Why does printing -1 as hexadecimal in Go and C produce different results?. For more information, please follow other related articles on the PHP Chinese website!