zoukankan      html  css  js  c++  java
  • 判断主机、网络字节序和互相转换

    大端字节序(big-endian):按照内存地址的增长方向,高位数据储存于低位地址。

    小端字节序(little-endian):按照内存地址增长方向,高位数据储存于高位地址。

    判断主机、网络字节序:

    #include <stdio.h>
    #include <arpa/inet.h> int main(void) {   unsigned short int h = 0x1234;   unsigned short int n;
      
    if (*((unsigned char *)&h) == 0x12) {     printf("big-endian ");   }   if (*((unsigned char *)&h) == 0x34) {     printf("little-endian ");   }
      n = htons(h);
      if (*((unsigned char *)&n) == 0x12) {
        printf("big-endian ");
      } else {
        printf("little-endian ");
      } 
      
    return 0; }

    或者:

    #include <stdio.h>  
    #include <arpa/inet.h>  
      
    int main(){  
        unsigned long a = 0x12345678;  
        unsigned char *p = (unsigned char *)(&a);  
        printf("主机字节序:%0x    %0x   %0x   %0x
    ",  p[0], p[1], p[2], p[3]);  
    
        unsigned long b = htonl(a);  //将主机字节序转化成了网络字节序  
                      
        p = (unsigned char *)(&b);  
      
        printf("网络字节序:%0x    %0x   %0x   %0x
    ",  p[0], p[1], p[2], p[3]);  
        
      return 0; }
    结果:
      主机字节序:78 56 34 12
      网络字节序:12 34 56 78

    转化:

    include <stdio.h>  
    #include <arpa/inet.h>  
    
    int main()  
    {  
        struct in_addr ipaddr;  
        unsigned long addr = inet_addr("192.168.1.100");  
        printf("addr = %u
    ", ntohl(addr));  
    
        ipaddr.s_addr = addr;  
        printf("%s
    ", inet_ntoa(ipaddr));    
        return 0;    
    } 
    结果:
      addr = 3232235876
      129.168.1.100

     参考:http://blog.csdn.net/msdnwolaile/article/details/50727653

    主机字节序与网络字节序的转换函数:htonl、ntohl、htons、ntohs     网址:http://blog.csdn.net/kulala082/article/details/53431473

  • 相关阅读:
    Orderly Class
    POJ2513 【并查集+欧拉路径+trie树】
    POJ2195 Going Home【KM最小匹配】
    洛谷P2604 最大流+最小费用最大流
    小数转分数
    威尔逊定理
    luogu P6564 [POI2007] 堆积木KLO 树状数组+dp
    Codeforces Round #644 (Div. 3) H——Binary Median 二分
    luogu P4933 大师 线性dp
    Codeforces Round #643 (Div. 2) D——Game With Array
  • 原文地址:https://www.cnblogs.com/coolYuan/p/8350727.html
Copyright © 2011-2022 走看看