Wednesday, March 28, 2012

Int to Char[4] and back again

I have decided to write a render system that creates a string class and as you add things to be rendered it add info to the string like a script. then when go to render, it pops off chars one at a time, reading it like a script and positioning objects on the screen based on their relative location the the camera definitions.  In order to do all this, I need a way to pass a int (4bytes) into 4 char values (1byte each).  Here is some example code I wrote to do just that:

 int CharsToInt( char top , char midt , char midb , char bot )  
 {  
      return(       
           (((int) top & 0xFF ) << 24) |   
           (((int) midt & 0xFF ) << 16) |   
           (((int) midb & 0xFF ) << 8) |   
           (((int) bot & 0xFF )) );  
 }  
 bool IntToChars( int INPUT , char *top , char *midt , char *midb , char *bot )  
 {  
      //going to rewrite this so that you just pass a pointer to a char[4].  
      //this would make passing from a String class easier  
      if( top && midt && midb && bot )  
      {  
           *top = (char) ( INPUT >> 24 ) & 0xFF;  
           *midt = (char) ( INPUT >> 16 ) & 0xFF;  
           *midb = (char) ( INPUT >> 8 ) & 0xFF;  
           *bot = (char) ( INPUT & 0xFF );  
           return true;  
      }  
      else  
           return false;  
 }  

EDIT: Rewrote it to be cleaner:

 int CharsToInt( char INPUT[] )  
 {  
      return(       
           (((int) INPUT[0] & 0xFF ) << 24) |   
           (((int) INPUT[1] & 0xFF ) << 16) |   
           (((int) INPUT[2] & 0xFF ) << 8) |  
           (((int) INPUT[3] & 0xFF )) );  
 }  
 bool IntToChars( int INPUT , char OUTPUT[] )  
 {  
      if( OUTPUT )  
      {  
           OUTPUT[0] = (char) ( INPUT >> 24 ) & 0xFF;  
           OUTPUT[1] = (char) ( INPUT >> 16 ) & 0xFF;  
           OUTPUT[2] = (char) ( INPUT >> 8 ) & 0xFF;  
           OUTPUT[3] = (char)  INPUT     & 0xFF;  
           return true;  
      }  
      else  
           return false;  
 }  

No comments:

Post a Comment