英文:
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 "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
答案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 "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:])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论