Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> The mentioned reason against using unsigned char (that shifting 128 left by 24 places results in UB) is also misleading

No, that reasoning is correct. Integer promotions are performed on the operands of a shift expression, meaning the left operand will be promoted to signed int even if it starts out as unsigned char. Trying to shift a byte value with highest bit set by 24 will results in a value not representable as signed int, leading to UB.



Thanks, I just noticed a small mistake in my example (I don't trigger the UB because I access b[0] containing 0x80 without shifting, however I meant to do it the other way around).

Still, adding an explicit cast to the left operand seems to be enough to avoid this, e.g.:

  uint32_t x = ((uint32_t)b[0]) << 24;
In summary, I think my point that using unsigned char would be appropriate in this case still stands.


> Still, adding an explicit cast to the left operand seems to be enough to avoid this

Indeed. See my other comment, https://news.ycombinator.com/item?id=27086482




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: