Skip to content

Instantly share code, notes, and snippets.

@spiegel-im-spiegel
Created October 19, 2017 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spiegel-im-spiegel/36fece8523575cdd005e83f9f37c9584 to your computer and use it in GitHub Desktop.
Save spiegel-im-spiegel/36fece8523575cdd005e83f9f37c9584 to your computer and use it in GitHub Desktop.
バイト列を整数に変換する簡単なお仕事メモ(Go言語) ref: http://qiita.com/spiegel-im-spiegel/items/1eb8bcb44c946aa5920d
package main
import (
"encoding/binary"
"fmt"
)
func main() {
octets := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
fmt.Printf("%#016x\n", binary.BigEndian.Uint64(octets)) //0x0001020304050607
fmt.Printf("%#016x\n", binary.LittleEndian.Uint64(octets)) //0x0706050403020100
}
package main
import (
"encoding/binary"
"fmt"
)
func main() {
value := uint64(0x0706050403020100)
buf := make([]byte, binary.MaxVarintLen64) //MaxVarintLen64 = 10
binary.BigEndian.PutUint64(buf, value)
fmt.Println(buf[:8]) //[7 6 5 4 3 2 1 0]
binary.LittleEndian.PutUint64(buf, value)
fmt.Println(buf[:8]) //[0 1 2 3 4 5 6 7]
}
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func main() {
octets := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
var value uint64
if err := binary.Read(bytes.NewReader(octets), binary.LittleEndian, &value); err != nil {
return
}
fmt.Printf("%#016x\n", value) //0x0706050403020100
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment