I'm in a the middle of creating a console based small game for our C programming class assignment and I decided to make it more presentable and unique by adding text colors and text backgrounds.
While I was on my quest searching for a solution, I've found this handy function that will do just the way I wanted for my project but the problem is that there is this part I do not understand:
WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
Where, BackC
and ForgC
are given integers and the data type WORD
is just a typedef for an unsigned short int. Specifically, what I don't understand is the ((BackC & 0x0F) << 4) + (ForgC & 0x0F)
part. Can anyone help me with this? I know that I can just use the function but I really want to know how the function works...Thanks!
Here is the full source code (colorExample.c)
#include <windows.h>
#include <stdio.h>
void SetColorAndBackground(int ForgC, int BackC);
int main()
{
SetColorAndBackground(10,1); //color value range 0 up-to 256
printf("what is text background color \n");
SetColorAndBackground(11,1);
printf("how about this?");
getch();
return 0;
}
void SetColorAndBackground(int ForgC, int BackC)
{
WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
return;
}