I am relatively new to C-programming and have found no answer yet. I want to send and receive integers, chars and longs as bytes over a TCP connection correctly. I have built this, but it doesn't work yet.
Sender:
int a = 12345;
char b = -1;
unsigned long c = 12174723939;
unsigned char array[256];
array[0] = (a >> 0) & 0xFF;
array[1] = (a >> 8) & 0xFF;
array[2] = (b >> 16) & 0xFF; //Is this correct for -1?
array[3] = (c >> 24) & 0xFF;
array[4] = (c >> 32) & 0xFF;
array[5] = (c >> 40) & 0xFF;
array[6] = (c >> 48) & 0xFF;
send(socket, array, sizeof(array),0); //or is &array better?
Receiver:
int a;
char b;
unsigned long c;
unsigned char array[256];
recv(socket, array, sizeof(array),0);
a |= (array[0] << 0) & 0xFF;
a |= (array[1] << 8) & 0xFF;
b |= (array[2] << 16) & 0xFF;
c |= (array[3] << 24) & 0xFF;
c |= (array[4] << 32) & 0xFF;
c |= (array[5] << 40) & 0xFF;
c |= (array[6] << 48) & 0xFF;
Is this correct? What is missing? Is there any other solution?
How is it done with the receiving part? I've read about big and little endians (with htonl/htons and ntohl/ntosl). Does someone have an example on how to implement it, for example, in this code?
a, b, cto 0, or change the first line of their respective assignments to (for example)a = (array[0] << 0) & 0xFF;They'll start out with junk data, you'll be ORing in valid data with the junk which will result in junk.