Copying a 4 element character array into an integer in C

后端 未结 6 1777
一个人的身影
一个人的身影 2020-12-17 23:00

A char is 1 byte and an integer is 4 bytes. I want to copy byte-by-byte from a char[4] into an integer. I thought of different methods but I\'m getting different answers.

6条回答
  •  醉话见心
    2020-12-17 23:33

    It's an endianness issue. When you interpret the char* as an int* the first byte of the string becomes the least significant byte of the integer (because you ran this code on x86 which is little endian), while with the manual conversion the first byte becomes the most significant.

    To put this into pictures, this is the source array:

       a      b      c      \0
    +------+------+------+------+
    | 0x61 | 0x62 | 0x63 | 0x00 |  <---- bytes in memory
    +------+------+------+------+
    

    When these bytes are interpreted as an integer in a little endian architecture the result is 0x00636261, which is decimal 6513249. On the other hand, placing each byte manually yields 0x61626300 -- decimal 1633837824.

    Of course treating a char* as an int* is undefined behavior, so the difference is not important in practice because you are not really allowed to use the first conversion. There is however a way to achieve the same result, which is called type punning:

    union {
        char str[4];
        unsigned int ui;
    } u;
    
    strcpy(u.str, "abc");
    printf("%u\n", u.ui);
    

提交回复
热议问题