将 32 位网络顺序转换为 C 格式的主机



我正在尝试将uint32_t从网络字节顺序转换为主机格式。我正在从存储在缓冲区中的 tcp 连接读取 4 字节,如下所示:

ssize_t read = 0;
char *file_buf;
size_t fb_size = 4 * sizeof(char);
file_buf = malloc(fb_size);
read = recv(socket_file_descriptor,file_buf,fb_size,0);

所以我将号码存储在file_buf但我想要一个号码,我该怎么做?

这看起来很简单:

ssize_t read = 0;
uint32_t myInteger;  // Declare a 32-bit uint.
// Pass a pointer to the integer, and the size of the integer.
read = recv(socket_file_descriptor,&myInteger,sizeof(myInteger),0);
myInteger = ntohl(myInteger); // Change from Network order to Host order.

这是我的做法。 请注意使用 ntohl() 将数据从网络字节序转换为主机字节序形式:

#include <stdio.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <sys/socket.h>
[...]
char file_buf[4];
if (recv(socket_file_descriptor,file_buf,fb_size,0) == sizeof(file_buf))
{
   uint32_t * p = (uint32_t *) file_buf;
   uint32_t num = ntohl(*p);
   printf("The number is %un", num);
}
else printf("Short read or network error?n");

一些操作系统(带有glibc的Linux,BSD(也具有特定于大小的字节序转换功能,以补充ntohl()ntohs()

#include <endian.h> // Might need <sys/endian.h> instead on some BSDs
void your_function(uint32_t bigend_int) {
  uint32_t host_int = be32toh(bigend_int);
}

编辑:

但是,由于您似乎可以轻松访问单个字节,因此始终采用Rob Pike的首选方法:

uint32_t host_int = (file_buf[3]<<0) | (file_buf[2]<<8) | (file_buf[1]<<16) | (file_buf[0]<<24);

相关内容

最新更新