"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does fmt.Printf Output \"-101\" for a Signed Integer Represented in Two\'s Complement?

Why Does fmt.Printf Output \"-101\" for a Signed Integer Represented in Two\'s Complement?

Published on 2024-11-13
Browse:792

Why Does fmt.Printf Output \

Two's Complement and fmt.Printf Binary Output

When computers use Two's complement to represent signed integers, a value like -5 is stored as the bit pattern "1111 1011." However, when trying to print this binary representation using fmt.Printf like this:

var i int8 = -5
fmt.Printf("%b", i)

The output unexpectedly shows "-101." Why is this happening, and is Two's complement being used internally?

The Issue with Binary Formatting

The discrepancy lies in the way fmt.Printf handles binary formatting. When formatting a negative signed integer, it converts it to a positive value and then appends a '-' sign before the formatted string.

Looking into the source code of fmt.Printf, we find that fmt.integer converts a signed integer to a positive value before formatting it:

    negative := signedness == signed && a 

Unsigned vs. Signed Output

To demonstrate this, consider this code:

var u uint8 = uint(i)
fmt.Printf("%b", u)

Here, we convert i to an unsigned integer before printing it. This time, the output correctly shows "11111011," which is the Two's complement of -5.

Conclusion

To correctly print the binary representation of a signed integer using fmt.Printf, we should first convert it to a positive integer using an unsigned type. This ensures that fmt.Printf does not automatically convert the value to a negative value and prepend a '-' sign.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3