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 any satisfactory answer in the above thread.
Here’s my requirement: I want to encode my data(say an integer) in a byte array and then transfer over the network and then decode at the other end and process it.
Here’s the encoding part:
const int MAX=5;
uint32_t a = 0xff00ffaa;
char byte_array[1024]; // this is the array to be transferred over the network
char buff[MAX]="";
sprintf(buff,"%4d",a);
memcpy(byte_array,buff,4);
// fill remaining stuff in the byte array and send it over the network
Here’s the decoding part:
const int MAX=5;
char buff[MAX]="";
strncat(buff,byte_array,4)
int i=atoi(buff);
// Work with i
Here are my questions :
1) Is the above code portable? I guess it is( please correct me)
2) Now, I wish to encode the byte array with 3 bytes (but the integer size is 4) i.e say the integer stores 0x00ffaabb and i just want the byte array to have ff int 0th index aa in the 1st index and bb in the 2nd index. How to do that?
snprinf doesn’t seem to work or may be i am missing something.
A person who has implemented any network protocol can easily help me out.
Decoding logic would still work i guess. (strncat(buff,byte_array,3) followed by atoi function call).
Here’s what the protocol says :
--------+--------+--------+--------+------------------------------
|Version| 3 byte length | Remaining stuff
--------+--------+--------+--------+------------------------------
Version is 1 byte, followed by 3 byte length of the message.
I hope I could clarify my problem
You’re storing as ASCII, where you should be storing the bytes themselves.
The encoding should be something like:
Notice how I made your target array unsigned, to indicate that it’s “raw bytes”, and not actually characters.
This serializes the variable
ainto the four first bytes ofbyte_arrayusing big-endian byte ordering, which is sort of the default for many network protocols.You may also want to see my answer here: question 1577161.