Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 简单的钻头设置和清洁_C++_Algorithm_Bitmap - Fatal编程技术网

C++ 简单的钻头设置和清洁

C++ 简单的钻头设置和清洁,c++,algorithm,bitmap,C++,Algorithm,Bitmap,我正在编写一本书上的练习。该程序应设置一个“位图图形设备”位,然后检查它们是否为1或0。设置函数已经编写好了,所以我只编写了test_bit函数,但它不起作用。 在main()中,我将第一个字节的第一位设置为1,因此该字节为10000000,然后我想测试它:10000000&10000000==10000000,所以不为空,但当我想打印它时,仍然得到false。怎么了 #include <iostream> const int X_SIZE = 32; const int Y_SI

我正在编写一本书上的练习。该程序应设置一个“位图图形设备”位,然后检查它们是否为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;
}
#包括
常数int X_SIZE=32;
const int Y_SIZE=24;
字符图形[X_大小/8][Y_大小];
内联无效集_位(常量整数x,常量整数y)
{
图形[(x)/8][y]|=(0x80>>((x)%8));
}
内联布尔测试位(常数整数x,常数整数y)
{
返回(图形[x/8][y]&(0x80>>((x)%8))!=0;
}
void print\u graphics(void)//此函数模拟位图图形设备
{
int x;
int-y;
整数位;
对于(y=0;y0;位=(位>>1))
{
如果((图形[x][y]&位)!=0)

std::cout我想你想要
0x80>
而不是
1>
中的
test\u位
。右移一位会产生零


也需要编写< C++ >(A&B)=0 < /COD>。<代码>=< /> >和<代码>!> < /C> >高于<代码>和<代码>,因此<代码> A&B!= 0 < /COD>被解析为“写代码< A&(b!=0)< /C> >(旧C/C++GOTCHA)

< P>在MSVC++中,得到编译器警告()< /P> 添加括号,它就可以工作,如下所示:

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
if(x)return true else return false
作为
return x
更易于读写。谢谢,我编辑了代码。也不需要在
return
语句中插入表达式。抱歉,我将其更改为0x80,因为我想从右向左,但这并不能解决我的问题。抱歉,我键入错误。