逆向-还原代码之little-or-big (Interl 64)

该代码段展示了如何使用C语言检查CPU的字节序,包括little-endian(小端序)和big-endian(大端序)的判断方法。通过创建联合体、位操作以及类型转换,确定了系统的字节序。测试函数test_one,checkCPU,test_two,test_thr和test_four分别以不同方式检测字节序。
摘要由CSDN通过智能技术生成

 

 

 

// 源代码

#include <stdio.h>

/*
 *    2016/9/29 yu    liang.
 */

int test_one(void)
{
    int i=1;  
    char *p=(char *)&i;  

    if(*p==1)    
           printf("Little_endian\n");        // Little_endian
    else
           printf("Big_endian\n");        
}

int checkCPU()
{
    {
       union w
       {  
              int a;
              char b;
       } c;

       c.a = 1;

       return(c.b ==1);    // [little endian]
    }
}

/*
 * 高字节存储在高地址是小端,高字节存储在低地址是大端
 */
int test_two()
{
    int *a = 1;            //    内存表示为0x00000001.指向编号为 1 的地址

   if ((char*)&a[3] == 1)    // &a[3] = &a + 3 = &a + sizeof(int) * 3 = a + 12 ====> 1 + 12 = 0xD, 见 c/array/slipt.c 验证
        printf("big\n");
    else
        printf("small\n");

    printf("0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]); // 0x1 0x5 0x9 0xd 0x11 0x15
}
 
int test_thr()
{
    union _test
    {
       int a;
       short b;
    }test;

    test.a = 0x12345678;

    if(test.b == 0x1234)
      printf("big\n");

    if(test.b == 0x5678)
       printf("small\n");
}

typedef unsigned char BYTE;
int test_four()
{
    unsigned int num,*p;

    p = &num;

    num = 0;

    *(BYTE *)p = 0xff;

    if(num == 0xff) {
        printf("The endian of cpu is little\n");
    }
    else {        //    num == 0xff000000
        printf("The endian of cpu is big\n");
    }
    return 0;
}


int main(void)
{
    int ret = -1;

   test_one();    

   ret = checkCPU();
   if (ret == 1)
       printf("[little endian]\n");    // [little endian]
   else if (ret == 0)
       printf("[big endian]\n");

   test_two();    // small
   test_thr();    // small
   test_four();    // The endian of cpu is little


    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值