4

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.

Radoslav Stoyanov
  • 1,460
  • 5
  • 27
  • 40

2 Answers2

3

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\n", *(*[8]byte)(unsafe.Pointer(&a)))
}
  • Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :) – Radoslav Stoyanov Nov 11 '18 at 06:07
  • Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the `unsafe` package to circumvent this protection. – Eternal_flame-AD Nov 11 '18 at 06:11
  • 2
    Don't use package `unsafe` for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use `unsafe` if truly justified, and only as a last resort. – icza Nov 11 '18 at 10:10
0

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\n", 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()
}