如何将代码“SetConsoleTextAttribute(hStdout, 192)”中的值 192 分解为前景色和背景色?

How do I decompose the value of 192 in the code `SetConsoleTextAttribute(hStdout, 192)` into foreground and background color?

我正在尝试了解 SetConsoleTextAttribute 的工作原理。

根据 consoleapi2.h 中的定义,此代码

#include <windows.h>
#include <stdio.h>
int main(){
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout, FOREGROUND_RED| BACKGROUND_BLUE);
    printf("  \n");
}

将控制台的前景色设置为红色和蓝色作为背景。

这段代码是检查组合值,即20。

printf("%d", FOREGROUND_RED | BACKGROUND_BLUE);

consoleapi2.h中的定义。

#define FOREGROUND_RED       0x0004 // text color contains red.
#define BACKGROUND_BLUE      0x0010 // background color contains blue.

到目前为止一切顺利,我清楚地理解了代码,直到我尝试了以下代码

#include <windows.h>
#include <stdio.h>
int main(){
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout, 192);
    printf("  \n");
}

我得到了

我自己补了192的值,不知道怎么用。如何将值分解为前景色和背景色?

有人可以给我线索吗?

wAttributes 参数 SetConsoleTextAttribute is of type WORD, i.e. a 16-bit unsigned integer. The lower 8 bits of the character attributes 对颜色信息进行编码。

下图说明了各个位的含义:

+===+===+===+===+===+===+===+===+
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |   bit
+===+===+===+===+===+===+===+===+
| I | R | G | B | I | R | G | B |   meaning
+---+---+---+---+---+---+---+---+
|  background   |  foreground   |   scope
+---+---+---+---+---+---+---+---+

RGB 是单独的红-绿-蓝颜色通道。如果设置了相应的位,则颜色通道打开,否则关闭。我指定强度。设置时它选择“亮”颜色,否则它指的是“暗”变体。

值 192 在二进制中是 0b1100'0000。设置背景颜色的 I 和 R 位,意思是“亮红色”。 None 的前景色位已设置,因此前景色为“黑色”。