位掩码结果不一致
Bit masking result inconsistency
我正在学习比特掩码,我对某些结果有疑问。下面是一些示例代码。
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "testFile.jpg" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
for (unsigned long long e = 0; e < lSize; e++){
unsigned short val1 = buffer[e] & 0x3;
cout << val1 << endl;
if (1 == val1){
}
if (1 == buffer[e] & 0x3){
//what does buffer[e] & 0x3 equal when I don't set it equal to an unsigned short.
}
}
因此,如果我输出val1
的值,我总是得到一个介于0和3之间的值。但是,当我在不为buffer[e] & 0x3
指定类型的情况下进行比较时,我并不总是得到相同的结果。我试图输出buffer[e] & 0x3
,看看它等于什么,但我得到了一个错误。所以我的问题是,当buffer[e] & 0x3
在第二个if语句中使用时,它可能的值是什么。谢谢
这是因为运算符优先级
7 == != For relational = and ≠ respectively
8 & Bitwise AND
所以==
优先于&
(1 == buffer[e] & 0x3)
和不是一回事吗
(1 == (buffer[e] & 0x3))
但是
((1 == buffer[e]) & 0x3)
(相当于(1 == buffer[e])
,因为用3掩蔽0或1没有效果)
你想要的是(1 == (buffer[e] & 0x3))
运算符优先级似乎有问题:http://en.cppreference.com/w/cpp/language/operator_precedence
1 == buffer[e] & 0x3
相当于
(1 == buffer[e]) & 0x3
相关文章:
- 如何查找导致结果不一致的代码
- 结果与 fstream::read 不一致
- 使用迭代器对向量的C 递归初始化产生不一致的结果
- boost::d ynamic_bitset 与 std::vector 的结果不一致<bool>?
- 使用不同的表达式计算同一整数时的结果不一致
- RapidJSON 在转换为字符串时产生不一致的结果
- 使用两种不同的方法遍历 Vector 的结果不一致
- GDI打印API StartDoc函数给出的结果不一致
- 位掩码结果不一致
- is_assignable<>结果不一致
- opencvmatchTemplate在计算机之间给出不一致的结果
- CPPCheck返回不一致的结果
- 异步函数产生不一致的结果
- 使用 strptime/strftime 的结果不一致
- 双精度数组和结果与 WIN32 和 WIN64 上的C++不一致
- 在opencv中findChessboardCorners()的结果不一致
- CUDA 共享内存 - 结果不一致
- C++/CImg结果不一致
- 从文件中读取的浮点值与计算结果不一致
- std::regex_search与gcc 4.9.1的结果不一致