2008년 1학기 시스템 프로그래밍 과제

 

2. Little Endian vs. Big Endian

Write a C program to test

whether it is running on a big endian or little endian architecture.

 

 

union을 이용하여 Endian의 영향을 받는 long int와

그렇지 않은 string으로 확인하였습니다.

 

 

코드

/*
*     Check_Machine_Endian (Little Endian vs. Big Endian)
*
*     This function check the machine's Endian.
*
*     - Argument
*     void
*
*     - Return
*     void
*   
*   
*    I use union.
*    union is shared memory in its variables.
*    Therefore I set unsigned long int variable and array of char variables that size is same unsigned long int.
*    and I set number 1 at unsigned long int variable.
*    So If this machine use Little Endian, then 1 is in lowest address in unsigned long int.
*    Hence array of char's fisrt element is set 1.
*    But If this machine use Big Endian, then 1 is in highest address in unsigned long int.
*    Hence array of char's first element is set 0.
*    If both 0 and 1 are not, then I don't know.
*
*
*     <- low   address   high ->
*     Big Endian
*     00 | 00 | 00 | 01
*
*     Little Endian
*     01 | 00 | 00 | 00
*
*
*     Made by Bak JinYeong, 2008.03.13*/
void Check_Machine_Endian(void)
{
    typedef union
    {
        unsigned long int word_size_int; // unsigned long int : machine word size
        unsigned char word_size_char_arr[sizeof(long int)]; // char(1byte) array that size is size of long int. Therefore It is same size of variable i.
    } word_size_int_char_u; // union name is word_size_int_char_u
    word_size_int_char_u int_char_union; // make the variable int_char_union. int_char_union's type is word_size_int_char_u
    int_char_union.word_size_int = 1; // set value 1 at sord_size_int in int_char_union
    if(1 == int_char_union.word_size_char_arr[0]) // if this machine use Little Endian,
    {
        printf("This machine is Little Endian\n"); // then 1 is in lowest address in unsigned long int.
    }
    else if(0 == int_char_union.word_size_char_arr[0]) // if this machine use Big Endian,
    {
        printf("This machine is Big Endian\n"); // then 1 is in highest address in unsigned long int.
    }
    else
    {
        printf("I don't know, what Endian this machine use.\n"); // I don't know what Endian
    }
}

크리에이티브 커먼즈 라이센스
Creative Commons License

글에 잘못된 점, 다른 점, 부족한 점이 있다면 지적해주세요.
댓글, 트랙백, 메일 모두 고맙습니다.

트랙백 주소 :: http://nosyu.pe.kr/trackback/1454

댓글을 달아 주세요

[로그인][오픈아이디란?]