gpt4 book ai didi

将#define 从字节转换为字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:18 25 4
gpt4 key购买 nike

我正在处理一些用于 BLE 连接的示例项目,部分代码如下所示:

#define UUID_BASE "\xaa\x82\xe0\x12\x69\xa2\x4b\xe7\x93\xe4\x19\xc9\x00\x00\x00\x00"

#define USER_ADVERTISE_SCAN_RESPONSE_DATA ("\x10"\UUID_BASE)

const struct data_struct
= {

.
.
.APP_BLE_ADV_DATA = USER_ADVERTISE_DATA,
.APP_BLE_SCAN_RESP_DATA = USER_ADVERTISE_SCAN_RESPONSE_DATA,
.
.
}

我想像这样表示 UUID_BASE:

#define UUID_BASE 0xaa, 0x82, 0xe0, 0x12, 0x69, 0xa2,0x4b, 0xe7, 0x93, 0xe4, 0x19, 0xc9, 0x00, 0x00,0x00,0x00

我的问题是,如何将我的 UUID_BASE 字节表示形式转换为它们的字符串表示形式,以便我可以按原样继续使用它们的代码。

非常感谢您的帮助。我无法在任何地方找到解决方案。

谢谢!!!

最佳答案

就这样写吧

#define UUID_BASE 0xaa, 0x82, 0xe0, 0x12, 0x69, 0xa2, 0x4b, 0xe7, 0x93, 0xe4, 0x19, 0xc9, 0xb2, 0xaf
#define USER_ADVERTISE_SCAN_RESPONSE_DATA {0x10, UUID_BASE, 0x0}

原因是,除了终止 \0 之外,只要将数据放入数组中,数据就完全相同。

这段代码

#define UUID_BASE 0xaa, 0x82, 0xe0, 0x12, 0x69, 0xa2, 0x4b, 0xe7, 0x93, 0xe4, 0x19, 0xc9, 0xb2, 0xaf
char dataA[] = {UUID_BASE, 0x0};

完全等同于这段代码

#define UUID_BASE_STR "\xaa\x82\xe0\x12\x69\xa2\x4b\xe7\x93\xe4\x19\xc9\xb2\xaf"
char dataB[] = UUID_BASE_STR;

你可以这样测试:

#include <string.h>
#include <stdio.h>

#define UUID_BASE_BYTES 0xaa, 0x82, 0xe0, 0x12, 0x69, 0xa2, 0x4b, 0xe7, 0x93, 0xe4, 0x19, 0xc9, 0xb2, 0xaf
#define UUID_BASE_STR "\xaa\x82\xe0\x12\x69\xa2\x4b\xe7\x93\xe4\x19\xc9\xb2\xaf"

int main() {
char dataA[] = {UUID_BASE_BYTES, 0x0};
char dataB[] = UUID_BASE_STR;

if(strcmp(dataA,dataB) == 0) {
printf("The strings are equal\n");
}
else {
printf("The strings are not equal\n");
}
}

这输出字符串相等

关于将#define 从字节转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42502786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com