Reputation: 815
I'm working on small client-server application written on C.
For sending unsigned 32-bit number to remote side used this code:
u_int32_t number = 123;
send(client_socket_, &number, 4, CLIENT_SOCKET_FLAGS);
For receiving this number on remote side used this code:
u_int32_t number;
recv(acceptor, &number, 4, SERVER_DATA_SOCKET_FLAGS);
printf("Number is: %u\n", number);
If client and server run on same architecture of processors (amd64
) - all works fine.
But if my client app launched on different processor architecture (mips
) - I getting invalid number on server (bytes order are inverted).
How I can architecturally independent serialize my number in binary format?
An important feature is the good performance of the binary serializer/deserializer. Also the solution should not be tied to a library.
Upvotes: 2
Views: 241
Reputation: 16243
Serialization
static void Ser_uint32_t(uint8_t arr [sizeof(uint32_t)], uint32_t value)
{
arr[0] = (value >> 24u) & 0xFFu;
arr[1] = (value >> 16u) & 0xFFu;
arr[2] = (value >> 8u) & 0xFFu;
arr[3] = (value >> 0u) & 0xFFu;
}
And de-serialization
static uint32_t DeSer_uint32_t(const uint8_t arr [sizeof(uint32_t)])
{
uint32_t x = 0;
x |= (uint32_t)(arr[0]) << 24u;
x |= (uint32_t)(arr[1]) << 16u;
x |= (uint32_t)(arr[2]) << 8u;
x |= (uint32_t)(arr[3]) << 0u;
return x;
}
Depending on the endianness you want you can correct the posted functions
Upvotes: 4
Reputation: 935
I prefer to use hexadecimal encoding.
Eg: 0xDEADBEEF
will literally be send as: <stx>DEADBEEF<etx>
.
This method has the advantage of not losing the ability to use ASCII control characters.
This method has the disadvantage that each number byte is doubled.
Conversion is easy, you can use a lookup table after masking a nibble.
It's a bit like using something like json, but more lightweight in execution.
Upvotes: 0