c++ - 添加和比较时签署约定

标签 c++ gcc casting unsigned-char

我有以下代码:

const uint8_t HEADER_SIZE = 0x08;
std::vector<uint8_t> a, b;
uint8_t x;

/* populate 'a', 'b'. Set 'x' */

for ( uint8_t i = 0; i < HEADER_SIZE; ++i )
{
    // The if statement (specifically the AND): Conversion to 'unsigned int' from 'int' may change the sign of the result [-Wsign-conversion]
    if ( x != ( a[i + HEADER_SIZE] & b[i] ) )
    {
         /* ... */
         break;
    }
}

我尝试了几乎所有的转换,但我似乎无法弄清楚为什么一个简单的 AND 会导致此警告。两个变量都是无符号的。有什么想法吗?

最佳答案

a[i + HEADER_SIZE]b[i] 都将被提升为 int,因为尽管它们都是无符号类型,但它们是比 int 更窄的类型。所有较窄的整数类型都被提升为 int(如果 int 可以表示被提升类型的所有值)或 unsigned int 用于所有构建在算术运算中。

将所有操作数显式转换为 unsigned int 应该消除警告:

unsigned int a_dash = a[i + HEADER_+SIZE];
unsigned int b_dash = b[i];
unsigned int x_dash = x;
if (x_dash != (a_dash & b_dash))
{ // ...

关于c++ - 添加和比较时签署约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675722/

相关文章:

linux - 如何检测我是否可以在盒子上运行为 gcc4 编译的可执行文件?

c++ - 模板替换和 SFINAE 中的私有(private)成员访问

python - 我需要更改pandas数据框中的几列类型。无法使用iloc这样做

c++ - 大型项目的头部防护装置

c++ - DirectX 深度缓冲不起作用

c++ - GL上下文销毁

c++ - 为自制操作码列表创建 C++ 编译器/链接器

c++ - 命名空间与包含的类同名,gcc 可以,clang 不行

ios - 在 Swift 中将 [NSObject, AnyObject] 转换为 [String, AnyObject]

c# - 为什么将值转换为 IEnumerable<T> 的行为会根据我初始化值的方式而有所不同?