2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Golang】8 バイト長の []byte を uint64 に変換する( 64ビット長のバイト・スライスをintに変換したい)

Last updated at Posted at 2022-04-25

Go 言語(以下 Golang)で、make([]byte, 8, 8) で作成した 8 バイト長のスライスを uint64符号なしint に変換したい。

golang "[]byte" uint64 変換」でググっても、逆の uint64 から []byte に変換するものや、int32リトルエンディアン後ろ詰め方式 だったり、符号あり前提のものばかりだったので、自分のググラビリティとして。

TL; DR (今北産業)

  • encoding/binary の Golang 標準パッケージを使う

  • binary.BigEndian.Uint64 関数を使う

  • 使い方: myUint64 := binary.BigEndian.Uint64(myByteSlice)

    my8byte := []byte{255, 0, 255, 0, 255, 0, 255, 0}
    myUint64 := binary.BigEndian.Uint64(my8byte)
    
    fmt.Printf(
    	"Type: %T\nHex : %x\nDec : %d\nBin : %064b\n\n",
    	myUint64,
    	myUint64,
    	myUint64,
    	myUint64,
    )
    // Output:
    // Type: uint64
    // Hex : ff00ff00ff00ff00
    // Dec : 18374966859414961920
    // Bin : 1111111100000000111111110000000011111111000000001111111100000000
    
    // 4 バイト長なら Uint32
    my4byte := []byte{255, 0, 255, 0}
    myUint32 := binary.BigEndian.Uint32(my4byte)
    
    fmt.Printf(
    	"Type: %T\nHex : %x\nDec : %d\nBin : %032b\n\n",
    	myUint32,
    	myUint32,
    	myUint32,
    	myUint32,
    )
    // Output:
    // Type: uint32
    // Hex : ff00ff00
    // Dec : 4278255360
    // Bin : 11111111000000001111111100000000
    

TS; DR cap 付き []byte スライスの結合・連結からの UINT64

2 つの 4 バイト長のデータを結合したかったのです。しかも append を使わないで。

具体的には byte スライス([]byte)をブツ切りにして、データをゴニョゴニョした 4 バイト長のデータを 2 つ作成し、1 つのlen = 8要素数 8 のスライスに結合したものを uint64 に変換したかったのです。

この時、cap 付き領域予約済みでイジッているのと、なるべくリアロケート領域を再確保させたくなかったのです。そのため append を使いたくなかったのです。

誰に需要があるのかわかりませんが、以下は 4 バイト長の 2 つのスライス を結合した、8 バイト・スライスを uint64 に変換する例です。

package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	a8 := []byte{49, 50, 51, 52} // ゴニョゴニョ済みの 4 バイトデータ
	b8 := []byte{65, 66, 67, 68} // ゴニョゴニョ済みの 4 バイトデータ

	var v = make([]byte, 8, 8) // なぜか 8 バイト cap で宣言されている変数

	copy(v, a8)     // 前半にコピー
	copy(v[4:], b8) // 後半にコピー

	fmt.Printf(
		"v = Len: %d\nCap: %d\nString: \"%s\"\nData: %d\n",
		len(v),
		cap(v),
		string(v),
		binary.BigEndian.Uint64(v), // ここがポイント
	)
	//
	// Output:
	// v = Len: 8
	// Cap: 8
	// String: "1234ABCD"
	// Data: 3544952156220179268
}

参考文献

2
1
0

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?