4 ms·
If you write it the naive way it works. uint8_t bytes[4]; uint32_t = bytes[0] << 24 + bytes[1] << 16 + bytes[2] << 8 + bytes[3]; The endianness is wha
by kevincox 4y ago
If you write it the naive way it works.
uint8_t bytes[4];
uint32_t = bytes[0] << 24 + bytes[1] << 16 + bytes[2] << 8 + bytes[3];
The endianness is whatever you write in the indexing and will be the same across architectures.
- e4m2 4y agoUnfortunately, the naive way also turns out to be wrong in C. uint8_t gets promoted to a signed int when shifting, which in turn causes undefined behavior for specific input. One way of fixing this is casting to the desired type before the shift, thus avoiding surprising conversions. On a side note, compiler warnings and sanitizers help with this kind of stuff greatly, use them if you have the option: https://godbolt.org/z/8oq9GTcze https://godbolt.org/z/8oq9GTcze
- zimmerfrei 4y ago>> uint8_t gets promoted to a signed int when shifting, which in turn causes undefined behavior for specific input. >> One way of fixing this is casting to the desired type before the shift, thus avoiding surprising conversions. Agree. For clarity, the "specific input" in the example would be a bytes[0] value larger than 127. This behavior is also explained here: https://wiki.sei.cmu.edu/confluence/display/c/INT34-C.+Do+not+shift+an+expression+by+a+negative+number+of+bits+or+by+greater+than+or+equal+to+the+number+of+bits+that+exist+in+the+operand https://wiki.sei.cmu.edu/confluence/display/c/INT34-C.+Do+no...