Use the binary or operator, and an integer whose precision is guaranteed to be at least 32 bits, which is the type unsigned long (although the type uint_least32_t could be also used).
Unsigned integer is used so any potential undefined and/or implementation defined behavior that is present when shifting signed integers is avoided.
This solution is independent of endianness.
unsigned long a = ( ( ( unsigned long )array[0] & 0xFF ) << 24 ) |
( ( ( unsigned long )array[1] & 0xFF ) << 16 ) |
( ( ( unsigned long )array[2] & 0xFF ) << 8 ) |
( ( ( unsigned long )array[3] & 0xFF ) << 0 ) ;
Casts to ( unsigned long )
are made to avoid intermediate implicit conversion to int
.
The & 0xFF
operation is there to remove unnecessary bits(if there were any in an unlikely scenario where CHAR_BIT != 8).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…