c++ - 放入现有缓冲区

标签 c++ int buffer

我有下面的代码,但我无法将 int 放入我的 buffer

unsigned char  buffer[1024];
buffer[0] = 0x44;
u_long fd = htonl(VERSION);
memcpy(buffer+1, &fd, 4);

你能帮帮我吗?

最佳答案

ntohl(buffer[1]);buffer[1] 的值将被获取(一个字符)并将被转换为 long。这将导致小端机器在 &buffer[1] 处取值,对于小于 224(unsigned) 的值显然为 0,正如您所调用的ntohl 前面的字节顺序颠倒。

如果你真的有兴趣查看缓冲区然后尝试

int *f =(int*) (&buffer[1]);
printf("\n %u \n", ntohl(*f));//Also *f but then you have to paste it in calculator to see allignment

关于c++ - 放入现有缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770601/

相关文章:

c++ - 链表函数cpp中的指针作用域

c++ - 预处理器 C++ 的工作

c - Int 到 char 数组。它是如何工作的?

python - 将 int 转换为 2 个字节的 Big-Endian

ios - 为什么我的数组没有填充从 for 循环成功获取的信息?

string - 如何在 Vala 中从 uint8[] 创建字符串?

java Bufferreader退出

c++ - 在虚析构函数中调用其他虚方法是否安全?

c++ - CMake - 找不到 Boost(缺少 : serialization) (found version "1.73.0"

c - 奇怪的读缓冲区