c++ - 如何将 char 数组解析为整数?

标签 c++ c arrays parsing integer

我有一个像这样的 char 数组的缓冲区:

char buf[4];
buf[0] = 0x82;
buf[1] = 0x7e;
buf[2] = 0x01;
buf[3] = 0x00;

我现在想将 char 2 和 3 一起读取为 big endian 中的 16 位无符号整数。如何使用 C(++) 标准工具执行此操作?

目前我只会知道手动解决方案:

int length = but[3];
length += but[2] << 8;

这对于 16 位整数来说很容易,但我还需要解析 32 位整数,这会使事情变得有点困难。那么标准库中是否有一个函数可以为我做这件事?

博多

最佳答案

您可以使用 ntohsntohl(在小端系统上):

#include <iostream>
#include <cstring>
#include <arpa/inet.h>
int main(){
    char buf[4];
    buf[0] = 0x82;
    buf[1] = 0x7e;
    buf[2] = 0x01;
    buf[3] = 0x00;
    uint16_t raw16;
    uint32_t raw32;
    memcpy(&raw16, buf + 2, 2); 
    memcpy(&raw32, buf    , 4); 
    uint16_t len16 = ntohs(raw16);
    uint32_t len32 = ntohl(raw32);
    std::cout << len16 << std::endl;
    std::cout << len32 << std::endl;
    return 0;
}

或者您可以交换字节并将其转换为适当的类型而不是移动。

关于c++ - 如何将 char 数组解析为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15989332/

相关文章:

c - 标量初始值设定项中的元素过多,我在 C 中不断遇到错误

c - 我们什么时候不应该使用#pragma pack?

c - 如何将内存重新分配给字符串数组

arrays - 在 matlab 中计算 3 维元胞数组的均值

c++ - 即使已指定,Visual Studio C++ 程序也找不到包含文件夹

c++ - 无法连接 QPushButton

c++ - OpenCV 的 cvAcc() 有什么作用?

static_assert 中的 C++ decltype

javascript - 为什么在 JavaScript 中反转数组等于常规数组?

python - 将文件加载到 2d numpy 数组中的有效方法