Home >Backend Development >Golang >Why Does Go Print Negative Integers as \'-ff\' While C Prints \'fffffffffffffff\' When Using \'%x\'?
When printing an integer value of -1 using the "%x" format specifier, Go and C behave differently. In Go, the output is "-1," while in C, it is "fffffffffffffff," as expected.
Go's Behavior
Go considers the "%x" format specifier to represent the value of the number in hexadecimal notation, regardless of whether it is negative. Thus, for -1, the hexadecimal value is "-ff."
C's Behavior
In contrast, C prints memory representations of integers using the "%x" specifier. Since -1 is typically stored in 2's complement form, its hexadecimal representation in memory is "fffffffffffffff."
Unifying Behavior with Type Conversions
To achieve C-like behavior in Go, one must explicitly convert the signed integer to its unsigned equivalent before applying the "%x" format specifier. For instance:
i := -1 // type int fmt.Printf("%x", uint(i)) // prints "fffffffffffffff"
Rationale for Go's Default
Rob Pike, a Go developer, explains the reasoning behind Go's default behavior:
"Why is that not the default [the unsigned format]? Because if it were, there would be no way to print something as a negative number, which as you can see is a much shorter representation."
The above is the detailed content of Why Does Go Print Negative Integers as \'-ff\' While C Prints \'fffffffffffffff\' When Using \'%x\'?. For more information, please follow other related articles on the PHP Chinese website!