This question already has an answer here:
How can a negative integer be represented as a binary in Go, using the two's complement notation?
For example:
n := int64(-1)
fmt.Printf("%b", n)
fmt.Println(strconv.FormatInt(n, 2))
Both lines print -1
. The result shoud be like ffffffffffffffff
.
</div>
I am sorry but did you mean you wanted to explore how int64 values are stored in the memory? You will need to use the unsafe
package to force reinterpret a value in go.
This code does what you want:
package main
import (
"fmt"
"unsafe"
)
func main() {
a := int64(-1)
fmt.Printf("%x
", *(*[8]byte)(unsafe.Pointer(&a)))
}
I also wrote a func to programmatically calculate the two's complement notation of a int64
in case that you just wanted to calculate the value:
package main
import (
"fmt"
"math/big"
)
func main() {
a := int64(-1)
fmt.Printf("%x
", TwoComplement(a))
}
func TwoComplement(val int64) []byte {
n := big.NewInt(val)
var r []byte
if n.Cmp(big.NewInt(0)) != -1 {
r = n.Bytes()
} else {
mask := big.NewInt(1)
mask.Lsh(mask, 64)
r = n.Add(n, mask).Bytes()
}
res := bytes.NewBuffer([]byte{})
for i := 0; i < 8-len(r); i++ {
res.WriteByte(0)
}
res.Write(r)
return res.Bytes()
}