November 16, 2008

Integer Splitting in C

For our make project we are using a single int of 9 digits to send communication to the different units. However first we needed a simple way to split the integer into separate parts. Sadly there is no split or charAt functions for integers, so I had to do some math to split it apart. This resulted in the functions below.

Just drop theses functions in...


int* protoConvertFrom(int num)
{
int *data;
data[3] = num % 100000;
data[2] = ( (num % 10000000) - data[3]) / 100000;
data[1] = ( (num % 100000000) - (data[3] + data[2]) ) / 10000000;
data[0] = ( (num % 1000000000) - (data[3] + data[2] + data[1]) ) / 100000000;
return data;
}

int protoConvertTo(int *part)
{
return (part[0] * 100000000) + (part[1] * 10000000) + (part[2] * 100000) + part[3];
}


API information...


int* protoConvertFrom(int num)


Splits an integer of 9 places (our protocol) into an array of four parts .

Parameters:

num: The integer received from the network.

Returns:

An array pointer of four integers... [0] = from, [1] = to, [2] = ID, [3] = value

Example:

int num = 131100001;
int *data = protoConvertFrom(num);
int ID = data[2];




int protoConvertTo(int *part)


Take a array pointer of 4 parts and combines then into a 9 digit integer (our protocol).

Parameters:

part: A pointer to an array.

Returns:

An a nine digit integer that is ready to send over the network

Example:

int *data = new int[4];
data[0] = 1; // from
data[1] = 3; // to
data[2] = 11; // ID
data[3] = 1; // value
int num = protoConvertTo(data);
// returns 131100001

No comments: