bod*_*ser 4 c c++ arrays parsing integer
我有像char数组这样的缓冲区:
char buf[4];
buf[0] = 0x82;
buf[1] = 0x7e;
buf[2] = 0x01;
buf[3] = 0x00;
Run Code Online (Sandbox Code Playgroud)
我现在想把char二和三一起读作big endian中的16Bit无符号整数.如何使用C(++)标准工具执行此操作?
目前我只知道手动解决方案:
int length = but[3];
length += but[2] << 8;
Run Code Online (Sandbox Code Playgroud)
这对16Bit整数来说很容易,但我还需要解析32Bit整数,这会让事情变得有点困难.那么标准库中有一个函数可以帮我吗?
博多
您可以使用ntohs和ntohl(在小端系统上):
#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;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以交换字节并将其转换为适当的类型而不是移位.