Copying a 4 element character array into an integer in C

后端 未结 6 1770
一个人的身影
一个人的身影 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:18

    Neither of the first two is correct.

    The first violates aliasing rules and may fail because the address of str is not properly aligned for an unsigned int. To reinterpret the bytes of a string as an unsigned int with the host system byte order, you may copy it with memcpy:

    unsigned int a; memcpy(&a, &str, sizeof a);
    

    (Presuming the size of an unsigned int and the size of str are the same.)

    The second may fail with integer overflow because str[0] is promoted to an int, so str[0]<<24 has type int, but the value required by the shift may be larger than is representable in an int. To remedy this, use:

    unsigned int b = (unsigned int) str[0] << 24 | …;
    

    This second method interprets the bytes from str in big-endian order, regardless of the order of bytes in an unsigned int in the host system.

提交回复
热议问题