Search code examples
gohexbufferbit-shift

how to work with hexstrings and bit shifting in golang


I have a hexademial string that I constructed from arduino sensor "5FEE012503591FC70CC8"

This value contains an array of with specific data placed at specific locations of the hex string. Using javascript I can convert the hexstring to a buffer then apply bit shifting operations to extract data, for example battery status like so

  const bytes = new Buffer.from("5FEE012503591FC70CC8", "hex");
  const battery = (bytes[8] << 8) | bytes[9];
  console.log(battery)

My attemp works but I feel its not optimal like the js way I have shown above

package main

import (
    "fmt"
    "strconv"
)

func main() {
    hex := "5FEE012503591FC70CC8"
    bat, err := strconv.ParseInt(hex[16:20],16,64)
    if err != nil {
        panic(err)
    }
    fmt.Println("Battry: ",bat)
}

I would really appreciate if someone could show me how to work with buffers or equivalent to the js solution but in go. FYI the battery information is in the last 4 characters in the hex string


Solution

  • The standard way to convert a string of hex-digits into a bytes slice is to use hex.DecodeString:

    import "encoding/hex"
    
    bs, err := hex.DecodeString("5FEE012503591FC70CC8")
    

    you can convert the last two bytes into an uint16 (unsigned since battery level is probably not negative) in the same fashion as your Javascript:

    bat := uint16(bs[8])<< 8 | uint16(bs[9])
    

    https://play.golang.org/p/eeCeofCathF

    or you can use the encoding/binary package:

    bat := binary.BigEndian.Uint16(bs[8:])
    

    https://play.golang.org/p/FVvaofgM8W-