2

While reading about bitmap processing in C++ I came across this block of code used for loading a color palette with data taken from a bitmap file:

//set Number of Colors
numColors = 1 << bmih.biBitCount;

//load the palette for 8 bits per pixel
if(bmih.biBitCount == 8) {
        colours=new RGBQUAD[numColours];
        fread(colours,sizeof(RGBQUAD),numColours,in);
}

where "bmih.biBitCount" is a predefined variable that already has a value. Why does the author declare numColors to equal 1 then assign the value bmih.biBitCount to that variable in the same line? what exactly does this do and what are the benefits of assigning a variable a value twice inline like this?

4

2 回答 2

4

为什么作者声明 numColors 等于 1 然后将值 bmih.biBitCount 分配给同一行中的该变量?

他没有;他将表达式的结果分配1 << bmih.biBitCountnumColors。分配最后发生。 <<按位左移运算符。这样想:

//set Number of Colors
numColors = (1 << bmih.biBitCount);
于 2012-09-10T19:20:44.980 回答
2

他没有,这是一个使用<<“流媒体”操作符让人们感到困惑的情况。

和运算符传统<<>>是位移运算符,这就是它们在这种情况下的含义。这些运算符将变量左移或右移多个位置。假设我们有x = 0b00001(并且您的编译器理解这样的二进制表示法)。x << 2会给出结果0b00100

于 2012-09-10T19:20:54.160 回答