From 5ce95fe490f66bde5b805abac7fe2786166b482b Mon Sep 17 00:00:00 2001 From: Shulhan Date: Wed, 6 Feb 2019 17:00:48 +0700 Subject: lib/bytes: add function to convert hexadecimal into byte --- lib/bytes/bytes.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'lib/bytes/bytes.go') diff --git a/lib/bytes/bytes.go b/lib/bytes/bytes.go index d1fee2c4..55c8a308 100644 --- a/lib/bytes/bytes.go +++ b/lib/bytes/bytes.go @@ -253,6 +253,36 @@ func PrintHex(title string, data []byte, col int) { fmt.Println() } +// +// ReadHexByte read two characters from data start from index "x" and convert +// them to byte. +// +func ReadHexByte(data []byte, x int) (b byte, ok bool) { + if len(data) < x+2 { + return 0, false + } + var y uint = 4 + for { + switch { + case data[x] >= '0' && data[x] <= '9': + b |= byte(data[x]-'0') << y + case data[x] >= 'A' && data[x] <= 'F': + b |= byte(data[x]-('A'-10)) << y + case data[x] >= 'a' && data[x] <= 'f': + b |= byte(data[x]-('a'-10)) << y + default: + return b, false + } + if y == 0 { + break + } + y -= 4 + x++ + } + + return b, true +} + // // ReadInt16 will convert two bytes from data start at `x` into int16 and // return it. -- cgit v1.3