c++ - 简单的钻头设置和清洁

标签 c++ algorithm bitmap

我正在编写书中的练习。这个程序应该设置一个“位图图形设备”位,然后检查它们中的任何一个是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 然后产生 0false resp.

关于c++ - 简单的钻头设置和清洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548332/

相关文章:

Android - 使用确定的 ProgressDialog 将位图保存到 SD 卡

c# - 不能使用 GDI+。可以使用 Windows API 调用在位图上绘制一条线吗?

c++ - 在 Visual Studio 中使用自制库

c++ - 在 C++ 中使用 ctags 查找用构造函数声明的变量

javascript - 按屏幕参数排序的文件

Java 4 : Sorting an array by 2 values

c++ - 当底层 OpenGL 状态被修改时,我是否应该声明一个方法 const

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

algorithm - 在有向图中找到 2 个节点之间的路径?

Vb.Net检查图像是否存在于另一个图像中