Using the MSDN color model in C++ and Arduino

The MSDN color model from Microsoft uses a simple math equation to take RGB color values and convert them into a single number of type long. In addition it also offers the ability to retrieve the RGB values from the concatenated number by shifting some bits to the right.This can come in handy if you are trying to cycle through the color spectrum without wanting to use processor intensive sine and cosine functions. To do this you can simply increment or decrement the RGB value and it will subsequently alter the individual RGB channels in a way that creates a logarithmic appearance of color shift. In the physical world this can be used to cycle through the colors of an RGB led.

//rgb color model
#include <iostream>

using namespace std;

double encodeVal( unsigned int red, unsigned int green, unsigned int blue)
	double val = red + (green*256) + (blue*256*256);	
	return val;	

void decodeVal(long rgb, unsigned int *R, unsigned int*G, unsigned int*B)
	*R = rgb&0x0000FF;
	*G = (rgb>>8)&0x0000FF;
	*B = (rgb>>16)&0x0000FF;

int main()
	unsigned int red, green, blue = 0;
	long rgb= 0;
	//encode a value of 255,20,0 RGB
	rgb = encodeVal(255,20,0);
	cout<<"encoded value is "<<rgb<<endl;
	//decode the value, save it to our variables
	decodeVal(rgb, &red, &green, &blue);
	cout<<"decoded values are:"<<endl<<"red "<<red<<endl<<"green "<<green<<endl<<"blue "<<blue<<endl;	


We start by encoding the RGB values of RED=255, Green= 20, and blue = 0. The encoded value is saved in rgb variable. we then decode the value back into the individual channels by using the decodeVal function. The pointers that are passed to the function are used to store the new RGB channel values.


encoded value is 5375
decoded values are:
red 255
green 20
blue 0

Leave a Reply