So, what is the ANSI Escape Code?
ANSI escape sequences are a standard, developed in the 70s, used to format outputs in
computer terminals. They are made of tags, making the console interpret what comes
next as a command instead of a simple string. Those codes are very useful and can make
many things like: move the cursor, apply bold or italic in text, clean the screen and
change the background color. However, I will just talk about the color codes in this
article.
The first two digits of the tag are the ASCII value of ESC, (27, 1Bh, 33o) and “[“ (91,
5Bh, 133o), the other part is an alphanumeric code representing some operation that
will be applied in the output. We have a stop tag too, which is the last part of the
command, and its function, as the name suggests, is to stop applying the modifications
in the console.
256 colors
With 256 texts and background color options.
This code prints a table with 256 shades of text colors generated using ANSI escape
code.
void print_256_colours_txt()
{
for (int i = 0; i < 256; i++)
{
if (i % 16 == 0 && i != 0)
cout << endl;
printf("\033[38;5;%dm %3d\033[m", i, i);
}
}
Codes of the 256 options of ANSI text colors
Background
This one generates all the options available with the 256 encodings.
Void print_256_colours_background()
{
for (int i = 0; i < 256; i++)
{
if (i % 16 == 0 && i != 0)
cout << endl;
printf("\033[48;5;%dm %3d\033[m", i, i);
}
}
Codes of the background colors available
If you look at the last pieces of code that I displayed, you will notice that they have a
number at the beginning of the code. The first one has a 38, this means that we are
working with the text color. The second one has a 48 and shows to the system that the
code is referent of console’s background.