为什么按位左移将uint8_t提升为更宽的类型 [英] Why does bitwise left shift promotes an uint8_t to a wider type
问题描述
我对uint8_t
有点困惑,很好奇当我向左流出位并发现
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;
打印出
212
468
而不是预期的
212
212
似乎<<
确实将uint8_t
提升了一些更宽的整数类型.为什么这样做呢?
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
推荐答案
几乎每个算术运算都执行所谓的常规算术转换.
Pretty much every arithmetic operation performs what's called the usual arithmetic conversions.
这可以追溯到几十年前.
This goes back decades.
首先,进行整体促销.
- 没有算术运算占用
uint8_t
,因此两个操作数将始终被提升.
- 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.
- 您可以通过将右侧的类型强制转换为
i
的类型来防止这种情况,但是根据上述规则,在这种情况下您什么都不会得到.
- 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.
(您可以在此处和结果是表达式的结果永远不会是uint8_t
;只是在j
的情况下,您已将其 back 强制转换为uint8_t
,并随之产生了环绕.
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.
这篇关于为什么按位左移将uint8_t提升为更宽的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!