gpt4 book ai didi

c++ - 在无符号char数组中存储0

转载 作者:行者123 更新时间:2023-12-02 09:47:44 25 4
gpt4 key购买 nike

我有一个像这样的unsigned char数组:

unsigned char myArr[] = {100, 128, 0, 32, 2, 9};
我正在使用 reinterpret_cast将其转换为 const char*,因为我必须将 const char*传递给方法。然后,此信息通过grpc和其他应用程序发送(基于erlang的信息将其存储在erlang Bin中)。但是我观察到的是,Erlang应用程序只收到了 << 100,128 >> ,此后什么也没有收到。是什么原因造成的?这是字符数组中的 0吗?有人可以解释如何处理 0数组中的 unsigned char吗?我确实读了很多答案,但是没有清楚的解释我的问题。

最佳答案

What could be causing this? Is it the 0 in the character array that is the problem here?


很有可能。
可能会将指针传递给的函数之一指定为接受指向空终止字符串的参数。您的数组碰巧被null终止,因为在索引2处包含空字符,该字符是字符串终止的位置。这种函数通常仅在数组以null终止的情况下才具有明确定义的行为,因此将指针传递给可能不包含null字符的任意二进制文件将非常危险。

Could someone explain how to handle the 0 in an unsigned char array?


不要将数组传递给期望以null结尾的字符串的函数。这包括大多数格式化的输出函数和 <cstring>中的大多数函数。该功能的文档应提及先决条件。
如果只有这些功能是您的选择,则可以将二进制数据编码为文本格式,然后在另一端对其进行解码。二进制数据的常用文本编码为 Base64 ,尽管它不一定是最佳的。

关于c++ - 在无符号char数组中存储0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64025657/

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