본문 바로가기
프로그래밍/시스템

구조체, 바이트 오더링, 자료형 (char, short)

by 써드아이 2017. 6. 22.
#include 

typedef struct {
    char red;
    char green;
    char blue;
    char alpha;
} color_t;

int main( void )
{
    color_t color = { 0x11, 0x22, 0x33, 0x44 };
    unsigned char *ptr = NULL;
    unsigned short *ptr_short = NULL;

    unsigned char array[] = { 0x11, 0x22, 0x33, 0x44 };
    color_t *ptr_color = NULL;

    unsigned short data_short = 0;


    printf( "\n\n" );

    printf( "*(unsigned int*) &color\n" );
    printf( "color : 0x%8x\n", *((unsigned int *) &color) );

    printf( "\n===================================\n\n" );


    ptr = (unsigned char*) &color;
    printf( "ptr = (unsigned char*) &color;\n" );

    printf( "ptr + 0 : 0x%x\n", *(ptr + 0) );
    printf( "      1 : 0x%x\n", *(ptr + 1) );
    printf( "      2 : 0x%x\n", *(ptr + 2) );
    printf( "      3 : 0x%x\n", *(ptr + 3) );

    printf( "\n===================================\n\n" );

    ptr_short = (unsigned short*) &color;
    printf( "ptr_short = (unsigned short*) &color;\n" );
    printf( "ptr_short + 0 : 0x%x\n", *(ptr_short + 0) );
    printf( "            1 : 0x%x\n", *(ptr_short + 1) );

    printf( "\n===================================\n\n" );

    ptr_color = (color_t*) array;
    printf( "ptr_color = (color_t*) array\n" );
    printf( "ptr_color->red   : 0x%x\n", ptr_color->red );
    printf( "           green : 0x%x\n", ptr_color->green );
    printf( "           blue  : 0x%x\n", ptr_color->blue );
    printf( "           alpha : 0x%x\n", ptr_color->alpha );

    printf( "\n===================================\n\n" );

    data_short = (unsigned short) array;
    printf( "data_short : 0x%x\n", data_short );

    printf( "\n===================================\n\n" );


    return 0;
}

*(unsigned int*) &color
color : 0x44332211

===================================

ptr = (unsigned char*) &color;
ptr + 0 : 0x11
      1 : 0x22
      2 : 0x33
      3 : 0x44

===================================

ptr_short = (unsigned short*) &color;
ptr_short + 0 : 0x2211
            1 : 0x4433

===================================

ptr_color = (color_t*) array
ptr_color->red   : 0x11
           green : 0x22
           blue  : 0x33
           alpha : 0x44

===================================

data_short : 0x19a8

===================================