将 C++ 字节结构转换/解析为 Go
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《将 C++ 字节结构转换/解析为 Go》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
我正在用go读取一些数据包,其中的字段是c++数据类型。我尝试解析数据,但读取的是垃圾值。
这是一个小例子 - c++ 中特定数据类型的数据规格表如下,
struct cartelemetrydata
{
uint16 m_speed;
uint8 m_throttle;
int8 m_steer;
uint8 m_brake;
uint8 m_clutch;
int8 m_gear;
uint16 m_enginerpm;
uint8 m_drs;
uint8 m_revlightspercent;
uint16 m_brakestemperature[4];
uint16 m_tyressurfacetemperature[4];
uint16 m_tyresinnertemperature[4];
uint16 m_enginetemperature;
float m_tyrespressure[4];
};
下面是我在 go 中定义的内容
type cartelemetrydata struct {
speed uint16
throttle uint8
steer int8
brake uint8
clutch uint8
gear int8
enginerpm uint16
drs uint8
revlightspercent uint8
brakestemperature [4]uint16
tyressurfacetemperature [4]uint16
tyresinnertemperature [4]uint16
enginetemperature uint16
tyrespressure [4]float32
}
对于实际的解组,我正在这样做 -
func decodePayload(dataStruct interface{}, payload []byte) {
dataReader := bytes.NewReader(payload[:])
binary.Read(dataReader, binary.LittleEndian, dataStruct)
}
payload := make([]byte, 2048)
s.conn.ReadFromUDP(payload[:])
telemetryData := &data.CarTelemetryData{}
s.PacketsRcvd += 1
decodePayload(telemetryData, payload)
我怀疑这是因为数据类型不相等,并且在将字节读入 go 数据类型时存在一些转换问题,而它们最初是作为 c++ 打包的。我该如何处理这个问题?
注意:我对发送的数据没有任何控制权,这是由第三方服务发送的。
正确答案
您面临的问题与结构成员的对齐有关。您可以阅读更多相关内容 here,但简而言之,c++ 编译器有时会添加填充字节,以保持架构所期望的自然对齐。如果不使用这种对齐方式,可能会导致性能下降甚至访问冲突。
例如,对于 x86/x64,大多数类型的对齐方式通常(但不一定保证)与大小相同。我们可以看到
#include <cstdint>
#include <type_traits>
std::size_t offsets[] = {
std::alignment_of_v<std::uint8_t>,
std::alignment_of_v<std::uint16_t>,
std::alignment_of_v<std::uint32_t>,
std::alignment_of_v<std::uint64_t>,
std::alignment_of_v<__uint128_t>,
std::alignment_of_v<std::int8_t>,
std::alignment_of_v<std::int16_t>,
std::alignment_of_v<std::int32_t>,
std::alignment_of_v<std::int64_t>,
std::alignment_of_v<__int128_t>,
std::alignment_of_v<float>,
std::alignment_of_v<double>,
std::alignment_of_v<long double>,
std::alignment_of_v<void*>,
};
编译为
offsets:
.quad 1
.quad 2
.quad 4
.quad 8
.quad 16
.quad 1
.quad 2
.quad 4
.quad 8
.quad 16
.quad 4
.quad 8
.quad 16
.quad 8
由于这些(和其他)实现细节,建议不要依赖内部表示。然而,在某些情况下,其他方法可能不够快(例如逐个字段序列化),或者您可能无法更改 c++ 代码,例如 op。
binary.Read 需要打包数据,但 c++ 将使用填充。我们需要使用依赖于编译器的指令,例如 #pragma pack(1) 或添加填充 go 结构。第一个选项不适用于 op,因此我们将使用第二个。
我们可以使用 offsetof 宏来确定结构体成员相对于结构体本身的偏移量。我们可以做类似的事情
#include <array>
#include <cstddef>
#include <cstdint>
using int8 = std::int8_t;
using uint8 = std::uint8_t;
using uint16 = std::uint16_t;
struct cartelemetrydata {
uint16 m_speed;
uint8 m_throttle;
int8 m_steer;
uint8 m_brake;
uint8 m_clutch;
int8 m_gear;
uint16 m_enginerpm;
uint8 m_drs;
uint8 m_revlightspercent;
uint16 m_brakestemperature[4];
uint16 m_tyressurfacetemperature[4];
uint16 m_tyresinnertemperature[4];
uint16 m_enginetemperature;
float m_tyrespressure[4];
};
// c++ has no reflection (yet) so we need to list every member
constexpr auto offsets = std::array{
offsetof(cartelemetrydata, m_speed),
offsetof(cartelemetrydata, m_throttle),
offsetof(cartelemetrydata, m_steer),
offsetof(cartelemetrydata, m_brake),
offsetof(cartelemetrydata, m_clutch),
offsetof(cartelemetrydata, m_gear),
offsetof(cartelemetrydata, m_enginerpm),
offsetof(cartelemetrydata, m_drs),
offsetof(cartelemetrydata, m_revlightspercent),
offsetof(cartelemetrydata, m_brakestemperature),
offsetof(cartelemetrydata, m_tyressurfacetemperature),
offsetof(cartelemetrydata, m_tyresinnertemperature),
offsetof(cartelemetrydata, m_enginetemperature),
offsetof(cartelemetrydata, m_tyrespressure),
};
constexpr auto sizes = std::array{
sizeof(cartelemetrydata::m_speed),
sizeof(cartelemetrydata::m_throttle),
sizeof(cartelemetrydata::m_steer),
sizeof(cartelemetrydata::m_brake),
sizeof(cartelemetrydata::m_clutch),
sizeof(cartelemetrydata::m_gear),
sizeof(cartelemetrydata::m_enginerpm),
sizeof(cartelemetrydata::m_drs),
sizeof(cartelemetrydata::m_revlightspercent),
sizeof(cartelemetrydata::m_brakestemperature),
sizeof(cartelemetrydata::m_tyressurfacetemperature),
sizeof(cartelemetrydata::m_tyresinnertemperature),
sizeof(cartelemetrydata::m_enginetemperature),
sizeof(cartelemetrydata::m_tyrespressure),
};
constexpr auto computepadding() {
std::array<std::size_t, offsets.size()> result;
std::size_t expectedoffset = 0;
for (std::size_t i = 0; i < offsets.size(); i++) {
result.at(i) = offsets.at(i) - expectedoffset;
expectedoffset = offsets.at(i) + sizes.at(i);
}
return result;
}
auto padding = computepadding();
编译为 (constexpr ftw)
padding:
.quad 0
.quad 0
.quad 0
.quad 0
.quad 0
.quad 0
.quad 1
.quad 0
.quad 0
.quad 0
.quad 0
.quad 0
.quad 0
.quad 2
因此,在 x86 上,我们需要在 enginerpm 之前有一个字节,在 tyrespressure 之前需要两个字节。
c++:
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <span>
using int8 = std::int8_t;
using uint8 = std::uint8_t;
using uint16 = std::uint16_t;
struct cartelemetrydata {
uint16 m_speed;
uint8 m_throttle;
int8 m_steer;
uint8 m_brake;
uint8 m_clutch;
int8 m_gear;
uint16 m_enginerpm;
uint8 m_drs;
uint8 m_revlightspercent;
uint16 m_brakestemperature[4];
uint16 m_tyressurfacetemperature[4];
uint16 m_tyresinnertemperature[4];
uint16 m_enginetemperature;
float m_tyrespressure[4];
};
int main() {
cartelemetrydata data = {
.m_speed = 1,
.m_throttle = 2,
.m_steer = 3,
.m_brake = 4,
.m_clutch = 5,
.m_gear = 6,
.m_enginerpm = 7,
.m_drs = 8,
.m_revlightspercent = 9,
.m_brakestemperature = {10, 11, 12, 13},
.m_tyressurfacetemperature = {14, 15, 16, 17},
.m_tyresinnertemperature = {18, 19, 20, 21},
.m_enginetemperature = 22,
.m_tyrespressure = {23, 24, 25, 26},
};
std::cout << "b := []byte{" << std::hex << std::setfill('0');
for (auto byte : std::as_bytes(std::span(&data, 1))) {
std::cout << "0x" << std::setw(2) << static_cast<unsigned>(byte)
<< ", ";
}
std::cout << "}";
}
结果
b := []byte{0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x07, 0x00, 0x08, 0x09, 0x0a, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x0d, 0x00, 0x0e, 0x00, 0x0f, 0x00, 0x10, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13, 0x00, 0x14, 0x00, 0x15, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x41, 0x00, 0x00, 0xc0, 0x41, 0x00, 0x00, 0xc8, 0x41, 0x00, 0x00, 0xd0, 0x41, }
让我们在 go 中使用它:
// type your code here, or load an example.
// your function name should start with a capital letter.
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type cartelemetrydata struct {
speed uint16
throttle uint8
steer int8
brake uint8
clutch uint8
gear int8
_ uint8
enginerpm uint16
drs uint8
revlightspercent uint8
brakestemperature [4]uint16
tyressurfacetemperature [4]uint16
tyresinnertemperature [4]uint16
enginetemperature uint16
_ uint16
tyrespressure [4]float32
}
func main() {
b := []byte{0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x07, 0x00, 0x08, 0x09, 0x0a, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x0d, 0x00, 0x0e, 0x00, 0x0f, 0x00, 0x10, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13, 0x00, 0x14, 0x00, 0x15, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x41, 0x00, 0x00, 0xc0, 0x41, 0x00, 0x00, 0xc8, 0x41, 0x00, 0x00, 0xd0, 0x41}
var datastruct cartelemetrydata
datareader := bytes.newreader(b[:])
binary.read(datareader, binary.littleendian, &datastruct)
fmt.printf("%+v", datastruct)
}
打印内容
{Speed:1 Throttle:2 Steer:3 Brake:4 Clutch:5 Gear:6 _:0 EngineRPM:7 DRS:8 RevLightsPercent:9 BrakesTemperature:[10 11 12 13] TyresSurfaceTemperature:[14 15 16 17] TyresInnerTemperature:[18 19 20 21] EngineTemperature:22 _:0 TyresPressure:[23 24 25 26]}
取出填充字节,结果失败。
好了,本文到此结束,带大家了解了《将 C++ 字节结构转换/解析为 Go》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
golang 生成的 WebAssembly 上的 Websocket?
- 上一篇
- golang 生成的 WebAssembly 上的 Websocket?
- 下一篇
- Java内存管理中的根集搜索算法有哪些?
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3179次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3390次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3418次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4525次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3798次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览

