aboutsummaryrefslogtreecommitdiff
path: root/lib/bytes
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
parent90fc696b6ac2e8e1c1ebb06fb518a3502f5749f2 (diff)
downloadpakakeh.go-5ce95fe490f66bde5b805abac7fe2786166b482b.tar.xz
lib/bytes: add function to convert hexadecimal into byte
Diffstat (limited to 'lib/bytes')
-rw-r--r--lib/bytes/bytes.go30
-rw-r--r--lib/bytes/bytes_test.go46
2 files changed, 76 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.
//
diff --git a/lib/bytes/bytes_test.go b/lib/bytes/bytes_test.go
index 3b79aced..2e1b3a24 100644
--- a/lib/bytes/bytes_test.go
+++ b/lib/bytes/bytes_test.go
@@ -164,6 +164,52 @@ func TestIsTokenAt(t *testing.T) {
}
}
+func TestReadHexByte(t *testing.T) {
+ cases := []struct {
+ in []byte
+ exp byte
+ expOK bool
+ }{{
+ in: []byte{},
+ }, {
+ in: []byte("x0"),
+ }, {
+ in: []byte("0x"),
+ }, {
+ in: []byte("00"),
+ expOK: true,
+ }, {
+ in: []byte("01"),
+ exp: 1,
+ expOK: true,
+ }, {
+ in: []byte("10"),
+ exp: 16,
+ expOK: true,
+ }, {
+ in: []byte("1A"),
+ exp: 26,
+ expOK: true,
+ }, {
+ in: []byte("1a"),
+ exp: 26,
+ expOK: true,
+ }, {
+ in: []byte("a1"),
+ exp: 161,
+ expOK: true,
+ }}
+
+ for _, c := range cases {
+ t.Log(c.in)
+
+ got, ok := ReadHexByte(c.in, 0)
+
+ test.Assert(t, "b", c.exp, got, true)
+ test.Assert(t, "ok", c.expOK, ok, true)
+ }
+}
+
func TestSkipAfterToken(t *testing.T) {
line := []byte(`abc \def ghi`)