I'm working with a HID driver, and this driver reads onto a []byte
buffer one of a few different reports. When I use hex.EncodeToString(buffer)
, it will return a string looking like either 0000
or 0100
or 0200
, etc. I want to check, using a switch, against the input from the HID device, and so I want to predefine these possibilities, up outside the main()
, how should I proceed?
I've tried these possibilities:
var LEFT []byte = []byte('0000')
// or
var LEFT []byte = `0000`
// or
var LEFT []byte = '0000'
// or
var LEFT []byte = '\x00\x00' // from the %q Printf verb
The alternative is that I call hex.DecodeString("0000")
inside the main() function.
Edit
A note on the solution offered, the EncodeToString
hex 0000
or 0100
is not four bytes but rather two:
"\x01"
== "01"
== '1'
so I can use, in order to get 0100, or 0200, as suggested:
var LEFT []byte{1,0}
// or
var LEFT []byte("\x01\x00")
A byte is defined with the byte data type. With the %c format verb, we print the character representation of the byte. We must explicitly set a variable to the byte type; otherwise, we get different types. In the code example, we have three variables.
We can convert a hex string to byte array in Java by first converting the hexadecimal number to integer value using the parseInt() method of the Integer class in java. This will return an integer value which will be the decimal conversion of hexadecimal value.
To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);
Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.
Use the following:
var (
left = []byte{0, 0}
right = []byte{1, 0}
// ... and so on
)
If you want to write it on hex:
var (
left = []byte{0x00, 0x00}
right = []byte{0x01, 0x00}
// ... and so on
)
You can also convert a string to a []byte:
var (
left = []byte("\x00\x00")
right = []byte("\x01\x00")
)
Use these variables in a switch statement like this:
switch {
case bytes.Equal(v, left):
fmt.Println("left")
case bytes.Equal(v, right):
fmt.Println("right"
}
It looks like you are working with 2 byte numbers encoded in little-endian format. If so, you can decode the bytes to an integer:
const (
left = 0
right = 1
)
switch binary.LittleEndian.Uint16(byteSlice) {
case left:
fmt.Println("left")
case right:
fmt.Println("right")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With