Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array?
I was looking for an answer but didn\'t get a
I've looked at this page a million times, and I really appreciate all the other answers for helping me out. Here is the stub I am using, which is unique from other answers because it can be used in a for loop:
void encode_int_as_char(int num, char *buf, int length){
int i;
for (i = 0; i < length; i++){
buf[i] = (char)(num >> ((8 * (length - i - 1)) & 0xFF));
}
}
int decode_int_from_char(char *enc, int length){
int i, num, cur;
num = 0;
for (i = 0; i < length; i++){
cur = (unsigned char) enc[i] << (8 * (length - i - 1));
num += (int) cur;
}
return num;
}