aboutsummaryrefslogtreecommitdiff
path: root/lib/bytes/bytes.go
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2019-02-06 17:00:48 +0700
committerShulhan <ms@kilabit.info>2019-02-06 17:00:48 +0700
commit5ce95fe490f66bde5b805abac7fe2786166b482b (patch)
treedf953b621ebacc481fea4eed1b54f962b6ed9258 /lib/bytes/bytes.go
parent90fc696b6ac2e8e1c1ebb06fb518a3502f5749f2 (diff)
downloadpakakeh.go-5ce95fe490f66bde5b805abac7fe2786166b482b.tar.xz
lib/bytes: add function to convert hexadecimal into byte
Diffstat (limited to 'lib/bytes/bytes.go')
-rw-r--r--lib/bytes/bytes.go30
1 files changed, 30 insertions, 0 deletions
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
@@ -254,6 +254,36 @@ func PrintHex(title string, data []byte, col int) {
}
//
+// 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.
//