Here is the original post by David Cary:

http://stackoverflow.com/questions/10566668/lossless-rgb-to-ycbcr-transformation

8-bit RGB to YCoCg and back with no errors. Here is the code I adapted from David's pseudo code:

Code:
#include <stdio.h>

signed char x,yy,diff,average, temp;
signed char Y,Co,Cg;
unsigned char R1, G1, B1, Rd, Gd, Bd;
unsigned long count;
unsigned short maxrederror, maxgreenerror, maxblueerror, Rct, Gct, Bct;

void RGB_to_YCoCg24(void){
    //forward_lift(red, blue);
    diff = (B1 - R1);
    average = (R1 + (diff >> 1));

    temp = average;
    Co = diff;

    diff = (temp - G1);
    average = (G1 + (diff >> 1));

    Y = average;
    Cg = diff;
}

void YCoCg24_to_RGB(void)
{
    x = (Y - (Cg >> 1));
    yy = (x + Cg);

    Gd = x;
    temp = yy;

    x = (temp - (Co >> 1));
    Bd = (x + Co);
    Rd = x;
}

int main(void){

for (Rct = 0; Rct <= 255; Rct ++)

for (Gct = 0; Gct <= 255; Gct ++)

for (Bct = 0; Bct <= 255; Bct ++)
{
{
{
R1 = Rct; G1 = Gct; B1 = Bct;
RGB_to_YCoCg24(); YCoCg24_to_RGB(); count ++;

if (Rd-R1 > maxrederror) {maxrederror = Rd-R1;}
else if (R1-Rd > maxrederror) {maxrederror = R1-Rd;}

if (Gd-G1 > maxgreenerror) {maxgreenerror = Gd-G1;}
else if (G1-Gd > maxgreenerror) {maxgreenerror = G1-Gd;}

if (Bd-B1 > maxblueerror) {maxblueerror = Bd-B1;}
else if (B1-Bd > maxblueerror) {maxblueerror = B1-Bd;}
}
}
}

printf("Colors tested: %d\n", count);
printf("Max red error    %d\n",maxrederror);
printf("Max green error  %d\n",maxgreenerror);
printf("Max blue error   %d\n",maxblueerror);

}