3 ms·
typically you shall avoid shift on signed integers, especially NEVER left shift on signed char|short|int|whatever. I limit shift strictly to unsigned integer n
by synergy20 4y ago
typically you shall avoid shift on signed integers, especially NEVER left shift on signed char|short|int|whatever.
I limit shift strictly to unsigned integer numbers.
- nayuki 4y agoFollowing this rule strictly can be tricky. uint16_t x = (...); uint16_t y = x << 15; Any arithmetic involving uint16_t will be promoted to some kind of int. If int is 16 bits wide, then uint16_t will be promoted to unsigned int before the shift, and all values of x are safe. Otherwise int is at least 17 bits wide, then uint16_t will be promoted to signed int before the shift. On a weird but legal platform where int is 24 bits wide, the expression (uint16_t)0xFFFF << 15 will cause undefined behavior. My workaround for this is to force promotion to unsigned int: (0U + x) << 15. https://stackoverflow.com/questions/39964651/is-masking-before-unsigned-left-shift-in-c-c-too-paranoid/39969562#39969562 https://stackoverflow.com/questions/39964651/is-masking-befo...