summaryrefslogtreecommitdiff
path: root/utils/utils.go
blob: 4e16ba3b62a92333593acd96857cbb47c339abc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package utils

import (
	"fmt"
)

// BytesToInt converts a slice of bytes to an int. Only 8- and 16-bit uints are
// supported, because those are the only thing the control tables contain.
func BytesToInt(b []byte) (int, error) {

	switch len(b) {
	case 1:
		return int(b[0]), nil

	case 2:
		return int(b[0]) | int(b[1])<<8, nil

	default:
		return 0, fmt.Errorf("invalid read length %d", len(b))

	}
}

// BoolToInt converts a bool to an int.
func BoolToInt(b bool) int {
	if b {
		return 1
	}
	return 0
}

// IntToBool converts an int to a bool.
func IntToBool(v int) bool {
	return (v != 0)
}

func Low(i uint16) byte {
	return byte(i & 0xFF)
}

func High(i uint16) byte {
	return Low(i >> 8)
}