代码之家  ›  专栏  ›  技术社区  ›  CodeRonin

用C语言将32位网络顺序转换为主机

  •  0
  • CodeRonin  · 技术社区  · 7 年前

    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);
    

    所以我把这个号码储存在文件里,但是我想要一个号码,我怎么做?

    3 回复  |  直到 7 年前
        1
  •  5
  •   abelenky    7 年前

    这看起来很简单:

    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.
    
        2
  •  1
  •   Jeremy Friesner    7 年前

    我会这样做的。注意使用 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 %u\n", num);
    }
    else printf("Short read or network error?\n");
    
        3
  •  1
  •   Shawn    7 年前

    一些操作系统(带有glibc、bsd的Linux)已经 size-specific 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);
    }
    

    编辑:

    preferred approach :

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