Monday, 26 October 2009

Colored Printf - Linux

1. Use ncurses
2. ANSI Codes :
Printing color strings uses only printf, without any alternative libraries such as ncurses? Yes, we can do that in any unix based operating system that support ANSI codes, I am not sure whether it works on either windows or mac, have no chance to try at the moment.

By feeding some magic characters to printf, you can manipulate your fore color, background color and even attributes. Lets look at a simple example to print “Hello World” in Bright Red with background black.

 #define BRIGHT 1 
#define RED 31 
#define BG_BLACK 40 
printf("%c[%d;%d;%dmHello World", 0x1B, BRIGHT,RED,BG_BLACK); 

Okay, the code above print the string with bright red but the color setting will remain, to reset back the color to default, refers the code as bellow:

 printf("%c[%dm", 0x1B, 0); 

The fore color, background color and attributes codes are shown as bellow


How’s the color magic works? 0×1B is a special code that used to do all the color settings. 0×1B is hex code equivalent to decimal 27. With character(27) and a open square blacket “[”, initiate the setting. The rest of the values are (attribute);(fore color);(background color) and it ends the setting with ” m “. So entire thing will be look like this:

printf("%c[%d;%d;%dm",27,1,33,40);

With that the rest of your print line will be in bright yellow with background color black.

I have transparent background, What if I want my default background instead of any color?
Simple, ignore the background color, How?

printf("%c[%d;%dmHello World%c[%dm\n",27,1,33,27,0);

The line above will print bright yellow “Hello World” with default bg color.

Wednesday, 24 June 2009

Kinds Of Memory

There are roughly 5 kinds of memory:

1) Statically allocated
2) Automatically allocated (stack/registers)
3) Dynamically allocated (heap)
4) Read-only memory
5) Program memory


1) All global variables and all variables declared with the keyword static. ANSI C/C++ states that they will be initialized to zero before the program starts. These are the only variables that have a known value at program start, without the programmer explicitly initializing them. RAM.

2) All local variables. (Local constants might end up here too, though that depends on the type of system.) RAM.

3) Memory explicity allocated by the programmer with malloc or new. RAM.

4) All global constants. Strings end up here since they are a special case treated as constant character arrays. On a PC: RAM. Non-PC systems: non-volatile read-only memory.

6) The code itself, as well as constant numeric values written in the code (#defines etc). On a PC: RAM. Non-PC systems: non-volatile read-only memory.