MDGSF Software Engineer

[C/C++] Endian

2017-01-16

0x12345678

Big-Endian:

低地址——->高地址

12 34 56 78

<br >

Little-Endian:

低地址——->高地址

78 56 34 12

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void vEndianTester()
{
    union endian_tester{
        unsigned int m_int;
        unsigned char m_byte[4];
    };

    endian_tester test;
    test.m_int = 0x0a0b0c0d;

    if(test.m_byte[0] == 0x0a) {
        printf("Big-endian\n");
    } else {
        printf("Little-endian\n"); //输出
    }
}

int main()
{
    vEndianTester();

    unsigned int uiNum = 0x12345678;
    char acBufBig[BUFSIZ] = {0};
    char acBufLittle[BUFSIZ] = {0};

    memcpy(acBufBig, (char*)&uiNum, sizeof(unsigned int));
    printf("acBufBig: %x %x %x %x\n", acBufBig[0], acBufBig[1], acBufBig[2], acBufBig[3]); //78 56 34 12

    *(unsigned int*)acBufLittle = uiNum;
    printf("acBufLittle: %x %x %x %x\n", acBufLittle[0], acBufLittle[1], acBufLittle[2], acBufLittle[3]); //78 56 34 12

    char * pc = (char*)&uiNum;
    printf("pc: %x %x %x %x\n", pc[0], pc[1], pc[2], pc[3]); //78 56 34 12

    char acLittle2[BUFSIZ] = {0};
    acLittle2[0] = pc[3];
    acLittle2[1] = pc[2];
    acLittle2[2] = pc[1];
    acLittle2[3] = pc[0];
    printf("acLittle2: %x %x %x %x\n", acLittle2[0], acLittle2[1], acLittle2[2], acLittle2[3]); // 12 34 56 78

    return 0;
}

weixingongzhonghao

Similar Posts

Comments