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

DDD
Release: 2024-11-01 13:31:29
Original
217 people have browsed it

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:

<code class="go">var i int8 = -5
fmt.Printf("%b", i)</code>
Copy after login

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:

<code class="go">    negative := signedness == signed && a < 0
    if negative {
        a = -a
    }</code>
Copy after login

Unsigned vs. Signed Output

To demonstrate this, consider this code:

<code class="go">var u uint8 = uint(i)
fmt.Printf("%b", u)</code>
Copy after login

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.

The above is the detailed content of Why Does fmt.Printf Output \'-101\' for a Signed Integer Represented in Two\'s Complement?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!