Converting a byte to an array and vice-versa
2010 April 18
Here are two super-useful Arduino utility functions I just devised for my thesis:
byte arrayToByte(int arr[], int len){
// Convert -1 to 0 and pack the array into a byte
int i;
byte result = 0;
for(i=len-1; i>=0; i--){
if(arr[i] == -1){
result &= ~(0 << i);
} else {
result |= (1 << i);
}
}
return result;
}
int* byteToArray(byte in){
int i, temp, out[8];
for(i=0; i<8; i++){ temp = (in >> i) & 1;
if(temp == 0) temp = -1;
out[i] = temp;
}
return out;
}
The first function takes in an array of up to 8 integers valued 1 or -1 and generates a corresponding byte; the second does the reverse. Easy to modify for other integer values.
Related Posts: