How to merge two array in a char array for sending over network
How to merge two array in a char array for sending over network
Suppose have two arrays of type float64
and uInt8
.
float64
uInt8
float64 readanalog[40];
uInt8 data1[88];
I want to merge them in a char array (or maybe char*, in byte form) and send them over the network. Every float 64 is 8 byte and every uInt8 is one byte, so I need an array of ((40*8) + 88) 408 byte. In converting two types in an array of byte and merge both arrays in one array, I tried so many ways but it was not successful. Can anyone help?
memcpy
Why do you need to merge them? If you're sending them over TCP, just send one after the other.
– molbdnilo
Aug 19 at 5:27
@molbdnilo I send merged data as one Kafka message. I know Kafka can get data in any form but for decreasing data size over the network I decided to convert them to the byte and send them to Kafka brokers.
– Soheil Pourbafrani
Aug 19 at 6:07
I don't see how converting eight bytes of
float64
to eight bytes of char
is going to save you any space.– molbdnilo
Aug 19 at 6:14
float64
char
@molbdnilo before that I used datatype
string
to merge data in it and send to Kafka brokers, but string
store some metadata and it's not just raw data (am I right?) so for efficiency, I decided to use the byte array.– Soheil Pourbafrani
Aug 19 at 6:19
string
string
1 Answer
1
You're lucky, I'm somehow in the mood to write some code...
char buffer[sizeof(readanalog) + sizeof(data1)];
memcpy(buffer, readanalog, sizeof(readanalog));
memcpy(buffer + sizeof(readanalog), data1, sizeof(data1));
Be aware (as denoted in the comments already), that you might get unexpected results if the two (or more) computers involved do not agree on the same floating point representation (although chances are that all use IEEE 754 for). Some fixed-point convention (e. g. not units, but thousands of) sometimes can be more appropriate... Additionally, you need to consider endianness (again chances are that all involved CPU use little endian).
Addendum. If you don't care much about data size, sometimes sending the data as plaintext is the right call. ASCII text is so close to universal it's not funny.
– user4581301
Aug 19 at 5:59
@user4581301 Good point, going a step further then is packing the data into some well-defined format such as JSON or XML
– Aconcagua
Aug 19 at 6:11
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Have you tried
memcpy
yet? Also watch out for the differences that can sometimes be found in how floating point numbers are implemented on different computers.– user4581301
Aug 19 at 5:09