3 ms·
Unfortunately, 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 s
by e4m2 4y ago
Unfortunately, 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...