From 6ab61f2c524686e479f9546d5ce2529f3b8eb7fe Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 4 Jan 2014 00:32:13 +0100 Subject: [PATCH] Added byte helpers --- bytes.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 bytes.go diff --git a/bytes.go b/bytes.go new file mode 100644 index 000000000..6bf381343 --- /dev/null +++ b/bytes.go @@ -0,0 +1,27 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" +) + +func NumberToBytes(num uint64, bits int) []byte { + buf := new(bytes.Buffer) + err := binary.Write(buf, binary.BigEndian, num) + if err != nil { + fmt.Println("binary.Write failed:", err) + } + + return buf.Bytes()[buf.Len()-(bits / 8):] +} + +func BytesToNumber(b []byte) (number uint64) { + buf := bytes.NewReader(b) + err := binary.Read(buf, binary.LittleEndian, &number) + if err != nil { + fmt.Println("binary.Read failed:", err) + } + + return +}