LoginSignup
4
0

More than 5 years have passed since last update.

Goでマイナス表示されたint32を「2の補数」で16進数表示をする

Last updated at Posted at 2019-02-05

32bitの2の補数を求めたい

タイトルが長くてわかりにくいですが、要するには整数の-100ffffff9cという表記になって欲しい(32bitの2の補数:tows complement)ということです。簡単な方法が見つからなかったので、binary経由の正攻法(?)を使用しました。

※ コメント欄に最適な方法を頂きましたので、そちらをご覧ください。

package main

import (
    "fmt"
    "bytes"
    "encoding/binary"
)

func main() {
    buf := new(bytes.Buffer)
    var num int32 = -100
    err := binary.Write(buf, binary.BigEndian, num)
    if err != nil {
        fmt.Println("", err)
    }
    fmt.Printf("%x", buf.Bytes())   
}

実行結果

ffffff9c

補足

-1を16bitで2の補数表記をすると0xffff。32bitの場合は0xffffffffとなります。C言語など整数のオーバーフローチェックがない言語では、キャストするだけで2の補数が取れるのですが、Goは実行時型チェックが強いがために遠回りをする必要がありました。

4
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0