zoukankan      html  css  js  c++  java
  • 从inet_pton()看大小端字节序

    #include<stdio.h>
    #include<netinet/in.h>
    #include<stdlib.h>
    #include<string.h>
    
    int main(){
    char * str=(char *)malloc(20);
    char * p="0.0.0.1";
    
    struct sockaddr_in servaddr;
    bzero(&servaddr,sizeof(servaddr));
    inet_pton(AF_INET,p,&servaddr.sin_addr);
    
    printf("0.0.0.1  converted to decimal %u
    ",servaddr.sin_addr);
    sprintf(str,"%u",servaddr.sin_addr);
    printf("decimal converted to string %s
    ",str);
    int *pnt=(int *)str;
    printf("string converted to decimal array %u
    ",*pnt);
    free(str);
    return;
    }

    运行结果如下

    0.0.0.1  converted to decimal 16777216
    decimal converted to string 16777216
    string converted to decimal array 926365233

    0.0.0.1 的二进制表示是00000000 00000000 00000000 00000001

    16777216 的二进制表示是00000001 00000000 00000000 00000000

    由此可见,0.0.0.1是按 big endian 字节序存储的。

    有一点需要明确,无论big/little endian, int或其他任何>=1B的变量的读取必然是由高到低读取)。另外,堆栈的增长是自高向低地址方向增长的,所以,0.0.0.1只有按如下方式存储才会被解释为16777216。
    ----stack高地址---00000001---00000000---00000000---00000000---stack低地址-----

    同理,926365233 的解释:
    '1677'占4个byte,正好被解释为一个整数,而 926365233(decimal)= 00110111 00110111 00110110 00110001(binary) ='7761'(ascii)
    显然,上面也是一个大端字节序。

    本程序算是一箭双雕解释了大小端字节序。另外,从apue上借鉴了一下 union方法判断字节序的方法,贴在下面,其实和上文异曲同工,

    #include<stdio.h>
    #include<stdlib.h>
    
    int checkCPU( )
    {
        {
               union w
               {  
                      int  a;
                      char b;
               } c;
               c.a = 1;
               return(c.b ==1);
        }
    }
    
    int main(){
    
    if(checkCPU()==1){
           printf("big end");
    }
    
    return;
    }
  • 相关阅读:
    Go语言开发Windows应用
    go 调用windows dll 的方法
    thinkPHP5 命名空间别名
    thinkPHP5 类库包注册
    thinkphp5 默认配置代码
    edusoho twig 引入文件功能
    edusoho 查找网址对应的控制器和模板页面
    启动Nginx 出现 nginx: [emerg] unknown directive "锘?user" 错误
    eduSOHO 首页模板 全部课程模块代码
    twig 模板控制器对应列表
  • 原文地址:https://www.cnblogs.com/zhaoyl/p/3683364.html
Copyright © 2011-2022 走看看