Home > Article > Backend Development > Why does fmt.Printf show a different binary representation for negative integers than expected in Go?
Two's Complement and fmt.Printf: Unraveling the Binary Representation Enigma
When working with signed integers, computers employ Two's complement to represent negative values. This differs from the typical binary representation, where the sign is indicated by a separate bit. For example, in Two's complement, the integer -5 is represented as 1111 1011.
However, printing the binary representation using fmt.Printf may yield unexpected results. For instance, the following code snippet:
var i int8 = -5 fmt.Printf("%b", i)
surprisingly outputs -101 instead of 1111 1011. This discrepancy has led to the question of whether Two's complement is truly being used for internal representation or if the formatting is obscuring the correct representation.
To shed light on this matter, we need to delve into how fmt.Printf formats binary numbers. The culprit resides in the fmt.integer function, which automatically converts negative signed integers to positive ones. This conversion involves negating the integer and prepending a - sign to the output string. Thus, the -101 output is a representation of - appended to the binary representation of 5.
To demonstrate this further, converting the signed integer to an unsigned integer and then formatting it using fmt.Printf produces the correct Two's complement representation:
var u uint8 = uint(i) fmt.Printf("%b", u)
This outputs 11111011, precisely the Two's complement of -5.
Therefore, the internal representation of signed integers in Go adheres to the Two's complement convention. The seemingly incorrect binary representation when formatting signed integers results from the automatic conversion and sign prepending performed by fmt.integer. Understanding this behavior is essential when working with signed integers and binary representations in Go.
The above is the detailed content of Why does fmt.Printf show a different binary representation for negative integers than expected in Go?. For more information, please follow other related articles on the PHP Chinese website!