본문 바로가기
IT/programming

[C/C++] C언어 Big-endian <-> Little-endian 상호 변환

by 어느해겨울 2022. 1. 13.

C언어 빅엔디안 <-> 리틀엔디안 상호 변환

C언어로 작성된 엔디안 체크 방법과 빅엔디안과 리틀엔디안 간 상호 교환하는 방법이다.

 

소스코드

1. 엔디안 체크 방법

int value = 1;
if( *(char *)&value == 0 ) {
	printf("Big-endian\n");

} else {
	printf("Little-endian\n");
}

 

2. 전체 코드

#include <stdio.h>

// function : change to little-endian
int to_le(int _target) {
    unsigned char bytes[4];
    int ret;

    bytes[0] = (unsigned char)((_target >> 24) & 0xff);
    bytes[1] = (unsigned char)((_target >> 16) & 0xff);
    bytes[2] = (unsigned char)((_target >> 8) & 0xff);
    bytes[3] = (unsigned char)((_target >> 0) & 0xff);

    ret = ((int)bytes[0] << 0)  |
          ((int)bytes[1] << 8)  |
          ((int)bytes[2] << 16) |
          ((int)bytes[3] << 24);

    return ret;
}

// function : change to big-endian
int to_be(int _target) {
    unsigned char bytes[4];
    int ret;

    bytes[0] = (unsigned char)((_target >> 0) & 0xff);
    bytes[1] = (unsigned char)((_target >> 8) & 0xff);
    bytes[2] = (unsigned char)((_target >> 16) & 0xff);
    bytes[3] = (unsigned char)((_target >> 24) & 0xff);

    ret = ((int)bytes[0] << 24) |
          ((int)bytes[1] << 16) |
          ((int)bytes[2] << 8) |
          ((int)bytes[3] << 0);

    return ret;
}


int main(int argc, char *argv[]) {
    int value = 1;

    // endian check
    if( *(char *)&value == 0 ) {
        printf("Big-endian\n");

    } else {
        printf("Little-endian\n");
    }


    // 1. change to big-endian
    value = to_be(value);
    if( *(char *)&value == 0 ) {
        printf("Big-endian\n");

    } else {
        printf("Little-endian\n");
    }


    // 2. change to little-endian
    value = to_le(value);
    if( *(char *)&value == 0 ) {
        printf("Big-endian\n");

    } else {
        printf("Little-endian\n");
    }
    return 0;
}

 

결과

muabow@muabow:~/dev/cpp_file$ gcc -o endian ./endian.c ; ./endian
Little-endian
Big-endian
Little-endian

 

끝.

 

 

댓글