Question

A VGA monitor programming involves writing 16-bit values to certain memory locations for getting a character printed on the screen. This is how the different bits in this 16-bit values translate into the character being printed on the screen :

enter image description here

I used enums to represent different background/foreground colors :

typedef enum
{ 
  eBlack , 
  eBlue , 
  eGreen ,
  eCyan,
  eRed,
  eMagenta,
  eBrown,
  eLightGrey,
  eDarkGrey,
  eLightBlue,
  eLightGreen,
  eLightCyan,
  eLightRed,
  eLightMagenta,
  eLightBrown,
  eWhite

} textColor ;

I wrote this function to create this 16-bit value based on three things, character user wants to print, foreground and background color he wants :

Assumptions : On my platform, int 32 bit, unsigned short 16 bit, char 8 bit

void printCharacterOnScreen ( char c , textColor bgColor, textColor fgColor ) 
{
    unsigned char higherByte = ( bgColor << 4 ) | (fgColor ) ;
    unsigned char lowerByte  = c  ;

    unsigned short higherByteAs16bitValue = higherByte & 0 ;
    higherByteAs16bitValue = higherByteAs16bitValue << 8 ;

    unsigned short lowerByteAs16bitValue = lowerByte & 0 ;

    unsigned short complete16bitValue = higherByteAs16bitValue & lowerByteAs16bitValue ;

    // Then write this value at the special address for VGA devices.
}

Q. Is the code correct and is it the write way to create such a value ? Is there some standard way to do this kind of operation ?

Q. Will my approach be platform independent ? Any other comments on the code ?

Was it helpful?

Solution

It is very close - but the line

unsigned short lowerByteAs16bitValue = lowerByte & 0 ;

will clear the lower byte. You probably want

unsigned short lowerByteAs16bitValue = lowerByte;

You don't really need the lowerByte, and could use c directly - but your code is more readable.

Next problem:

unsigned short complete16bitValue = higherByteAs16bitValue & lowerByteAs16bitValue ;

Again, you are using the & operator. I think you mean to use | (OR) as you did a few lines earlier.

While this now looks "portable", you still need to be careful when writing to the hardware since low-endian and high-endian platforms may switch the byte around - so while your code works up to the point of returning the correct 16 bit word, you may need to pay attention to how that word gets written to the VGA card. That's the line you had commented out... but it is critically important!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top