I am writing one socket client server application where server need to send one large buffer to client and all buffer should be processed separate, so I want to put buffer length in buffer so client read length amount of data from buffer and process.
To put length value I need to divide integer value in one byte each and store it in buffer to be sent over socket. I am able to break integer into four parts but at time of joining I am not able to retrieve correct value. To demonstrate my problem I have written one sample program where I am dividing int into four char variables and then join it back in another integer. Goal is that after joining I should get same result.
Here is my small program.
#include <stdio.h>
int main ()
{
int inVal = 0, outVal =0;
char buf[5] = {0};
inVal = 67502978;
printf ("inVal : %d\n",inVal);
buf[0] = inVal & 0xff;
buf[1] = (inVal >> 8) & 0xff;
buf[2] = (inVal >> 16) & 0xff;
buf[3] = (inVal >> 24) & 0xff;
outVal = buf[3];
outVal = outVal << 8;
outVal |= buf[2];
outVal = outVal << 8;
outVal |= buf[1];
outVal = outVal << 8;
outVal |= buf[0];
printf ("outVal : %d\n",outVal);
return 0;
}
Output inVal : 67502978 outVal : -126
Please let me know what I am doing wrong.
Thanks!
ints? – Peter A. Schneider 3 hours ago