Two's complement and fmt.Printf

后端 未结 2 1460
遥遥无期
遥遥无期 2021-01-02 08:29

So computers use Two\'s complement to internally represent signed integers. I.e., -5 is represented as ^5 + 1 = \"1111 1011\".

However, trying to print the binary re

相关标签:
2条回答
  • 2021-01-02 09:13

    I believe the answer lies in how the fmt module formats binary numbers, rather than the internal format.

    If you take a look at fmt.integer, one of the very first actions that the function does is to convert the negative signed integer to a positive one:

       165      negative := signedness == signed && a < 0
       166      if negative {
       167          a = -a
       168      }
    

    There's then logic to append - in front of the string that's output here.

    IOW -101 really is - appended to 5 in binary.

    Note: fmt.integer is called from pp.fmtInt64 in print.go, itself called from pp.printArg in the same function.

    0 讨论(0)
  • 2021-01-02 09:24

    Unsafe pointers must be used to correctly represent negative numbers in binary format.

    package main
    
    import (
        "fmt"
        "strconv"
        "unsafe"
    )
    
    func bInt8(n int8) string {
        return strconv.FormatUint(uint64(*(*uint8)(unsafe.Pointer(&n))), 2)
    }
    
    func main() {
        fmt.Println(bInt8(-5))
    }
    

    Output

    11111011
    
    0 讨论(0)
提交回复
热议问题