Converting from an integer to its binary representation

前端 未结 7 1328
野的像风
野的像风 2020-12-24 00:09

Has anyone got an idea if there is any inbuilt functionality in Go for converting from any one of the numeric types to its binary number form.

For example, if

7条回答
  •  伪装坚强ぢ
    2020-12-24 00:44

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

    package main
    
    import (
        "fmt"
        "strconv"
        "unsafe"
    )
    
    func bInt(n int64) string {
        return strconv.FormatUint(*(*uint64)(unsafe.Pointer(&n)), 2)
    }
    
    func main() {
        fmt.Println(bInt(-1))
    }
    

    https://play.golang.org/p/GxXjjWMyC4x

提交回复
热议问题