Converting from an integer to its binary representation

前端 未结 7 1324
野的像风
野的像风 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:49

    An alternate way for the accepted answer would be to simply do

    s := fmt.Sprintf("%b", 123)
    fmt.Println(s)                 // 1111011
    

    For a more rich representation you can use the unsafe package(strongly discouraged) as

    a := int64(123)
    byteSliceRev := *(*[8]byte)(unsafe.Pointer(&a))
    byteSlice := make([]byte, 8)
    for i := 0; i < 8; i++ {
        byteSlice[i] = byteSliceRev[7 - i]
    }
    fmt.Printf("%b\n", byteSlice)
    

    This works for negative integers too.

提交回复
热议问题