问题
I was a bit messing around with uint8_t
and was curious what happens when I outflow bits to the left and found that
uint8_t i = 234;
uint8_t j = (i << 1);
auto k = (i << 1);
std::cout << (int)j << std::endl;
std::cout << k << std::endl;
prints out
212
468
and not the expected
212
212
It seems like <<
does promote an uint8_t
too some wider integer type. Why does it do this?
Here a link where you see it in action
回答1:
Pretty much every arithmetic operation performs what's called the usual arithmetic conversions.
This goes back decades.
First, integral promotions are performed.
- No arithmetic operation takes
uint8_t
so both of your operands will always be promoted.
After that, a common type is found and conversions take place if necessary.
- You can prevent this by casting the right-hand-side to the type of
i
but, per the above rule, that doesn't get you anything in this case.
(You can learn more about this process here and here.)
The upshot is that the result of your expression is never going to be uint8_t
; it's just that in the case of j
you've cast it back to uint8_t
, with the wraparound that consequently ensues.
来源:https://stackoverflow.com/questions/57609263/why-does-bitwise-left-shift-promotes-an-uint8-t-to-a-wider-type