我正在编写书中的练习。这个程序应该设置一个“位图图形设备”位,然后检查它们中的任何一个是1还是0。设置函数已经写好了,所以我只写了test_bit函数,但它不起作用。 在 main() 中我将第一个字节的第一位设置为 1,所以字节是 10000000,然后我想测试它:10000000 & 10000000 == 10000000,所以不为空,但是当我想打印它时我仍然得到 false出去。怎么了?
#include <iostream>
const int X_SIZE = 32;
const int Y_SIZE = 24;
char graphics[X_SIZE / 8][Y_SIZE];
inline void set_bit(const int x, const int y)
{
graphics[(x)/8][y] |= (0x80 >> ((x)%8));
}
inline bool test_bit(const int x, const int y)
{
return (graphics[x/8][y] & (0x80 >> ((x)%8)) != 0);
}
void print_graphics(void) //this function simulate the bitmapped graphics device
{
int x;
int y;
int bit;
for(y=0; y < Y_SIZE; y++)
{
for(x = 0; x < X_SIZE / 8; x++)
{
for(bit = 0x80;bit > 0; bit = (bit >> 1))
{
if((graphics[x][y] & bit) != 0)
std::cout << 'X';
else
std::cout << '.';
}
}
std::cout << '\n';
}
}
main()
{
int loc;
for (loc = 0; loc < X_SIZE; loc++)
{
set_bit(loc,loc);
}
print_graphics();
std::cout << "Bit(0,0): " << test_bit(0,0) << std::endl;
return 0;
}
最佳答案
在 MSVC++ 中,我收到编译器警告 ( C4554 'operator' : check operator precedence for possible error; use parentheses to clarify precedence )
添加括号,效果如下:
inline bool test_bit(const int x, const int y)
{
return ( ( graphics[x/8][y] & (0x80 >> ((x)%8)) ) != 0);
// ^ ^ Added parentheses
}
解释:
问题出在订单上。原始行将首先评估 (0x80 >> ((x)%8) != 0
,即 true
,或 1
作为整数. 和 0x80 & 0x01
然后产生 0
或 false
resp.
关于c++ - 简单的钻头设置和清洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548332/