Thursday, July 24, 2008

Quick code sample

A rather innoculous C++ class (of static functions) for placing/extracting 32-bit ints and floats to/from a C-style byte array. As mentioned in the comment, this was written for use in UDP network programming.

DEFAULTARRAYLENGTH is a constant declared elsewhere. It's helpful if the majority of the char* buffers passed in are of the same, fixed size.



/// implements some Bit library type functions for use with UDP/char* buffers

class PBitLib
{
public:

// assumes 32bit int
static void toBuffer( int num, char* buffer, int start = 0, int buflen = DEFAULTARRAYLENGTH )
{
if (buflen < 4 + start)
return;

int x = num;
unsigned char * bytes = (unsigned char *) &x;

for (int i = 0; i < 4; i++)
buffer[i+start] = (char) (bytes[i]);
};

// assumes 32bit float
// copies float into buffer from buffer[start] to buffer[start+3]
static void toBuffer( float num, char* buffer, int start = 0, int buflen = DEFAULTARRAYLENGTH )
{
if (buflen < 4 + start)
return;

float x = num;
unsigned char * bytes = (unsigned char *) &x;

for (int i = 0; i < 4; i++)
buffer[i+start] = (char) (bytes[i]);
};

// assumes 32bit int
static int bufferToInt( char* buffer, int start = 0, int buflen = DEFAULTARRAYLENGTH )
{
if (buflen < 4 + start)
return 0;

unsigned char bytes[4];
for (int i = 0; i < 4; i++)
bytes[i] = (unsigned char) buffer[i+start];

int num = *(int*)(bytes);
return num;
};


//
static float bufferToFloat( const char* buffer, int start = 0, int buflen = DEFAULTARRAYLENGTH )
{
if (buflen < 4 + start)
return 0;

unsigned char bytes[4];
for (int i = 0; i < 4; i++)
bytes[i] = (unsigned char) buffer[i+start];

float num = *(float*)(bytes);
return num;
};
};

No comments: