how to work with hexstrings and bit shifting in golang

huangapple go评论93阅读模式
英文:

how to work with hexstrings and bit shifting in golang

问题

我有一个由Arduino传感器构建的十六进制字符串:"5FEE012503591FC70CC8"。

这个值包含一个数组,其中特定数据放置在十六进制字符串的特定位置。使用JavaScript,我可以将十六进制字符串转换为缓冲区,然后应用位移操作来提取数据,例如电池状态,如下所示:

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

我的尝试是有效的,但我觉得不如上面展示的JavaScript方式优化。

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("Battery:", bat)
}

如果有人能向我展示如何使用缓冲区或等效的Go解决方案,我将非常感激。顺便说一下,电池信息位于十六进制字符串的最后4个字符中。

英文:

I have a hexademial string that I constructed from arduino sensor &quot;5FEE012503591FC70CC8&quot;

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(&quot;5FEE012503591FC70CC8&quot;, &quot;hex&quot;);
  const battery = (bytes[8] &lt;&lt; 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 (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

func main() {
	hex := &quot;5FEE012503591FC70CC8&quot;
	bat, err := strconv.ParseInt(hex[16:20],16,64)
	if err != nil {
		panic(err)
	}
	fmt.Println(&quot;Battry: &quot;,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

答案1

得分: 1

将十六进制数字字符串转换为字节切片的标准方法是使用hex.DecodeString函数:

import "encoding/hex"

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

你可以按照与JavaScript相同的方式将最后两个字节转换为uint16类型(无符号,因为电池电量可能不是负数):

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

或者你可以使用encoding/binary包:

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

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

import &quot;encoding/hex&quot;

bs, err := hex.DecodeString(&quot;5FEE012503591FC70CC8&quot;)

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])&lt;&lt; 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-

huangapple
  • 本文由 发表于 2021年10月16日 01:22:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/69588440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定