gpt4 book ai didi

c++ - 为什么 unsigned char << unsigned char 的结果不是 unsigned char

转载 作者:可可西里 更新时间:2023-11-01 18:21:05 29 4
gpt4 key购买 nike

我从左移得到的结果我找不到解释。

unsigned char value = 0xff; // 1111 1111
unsigned char = 0x01; // 0000 0001

std::cout << "SIZEOF value " << sizeof(value) << "\n"; // prints 1 as expected
std::cout << "SIZEOF shift " << sizeof(shift) << "\n"; // prints 1 as expected

std::cout << "result " << (value << shift) << "\n"; // prints 510 ???

std::cout << "SIZEOF result " << sizeof(value << shift) << "\n"; // prints 4 ???

我原以为结果是 1111 1110 但我得到的是 int(?),值为 1 1111 1110

如何将 unsigned char 的位向左移动,以便截断位,结果为 1111 1110?

我想做的是读取一系列字节并将它们解释为不同长度(1-32 位)的整数。

F0        F5
1111 0000 1111 0101

可能是

0F (first 4 bits)
0F (next 8 bits)
05 (last 4 bits)

这与不对小于 int 的类型进行算术运算有关吗?

最佳答案

引用 2011 年标准的一些草案:

5.8 Shift operators [expr.shift]

...

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.

4.5 Integral Promotions [conv.prom]

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int

...

所以,value被提升为int , 以及 value << shift 的类型是提升的左操作数的类型,即 int .

您可以通过以下方式之一实现您想要的结果:

std::cout << "result " << ((unsigned char)(value << shift)) << "\n";
std::cout << "result " << ((value << shift)&0xff) << "\n";

关于c++ - 为什么 unsigned char << unsigned char 的结果不是 unsigned char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713490/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com