I'm working with Particle Photon microcontroller and need to send a value >> 255 via TCP. I would need to convert this into an array of uint8_t so that I can use the client.write((int8_t *data), int sizeof(packet)); how can I achieve it?
2 Answers
If possible, pick a consistent "endianness" for your data - "big endian" is typical for binary network protocols - it's used for the header fields in IP, UDP, TCP, etc.
Given that, you can then use the htonX family of functions to convert the data from host format (whichever endian format that might be) to network format and then ntohX on receipt to convert it back again, e.g.:
uint32_t netword = htonl(data); [ On big-endian systems these functions become a "no-op" ]
EDIT oh - I missed the 'microcontroller' bit - chances are you don't have those functions available :(
15 Comments
ntohX(v) == v, i.e. it's the identity function.htonl(x) you're saying x is in host byte order, and you want it converted to network byte order. It doesn't matter if it was already in network byte order, because you're telling it it's host byte order and you want it swapped.htonX when writing to the wire and ntohX when reading from the wire.used what ScruffR said on this post
EDIT previous version wasn't actually doing the job properly. adopted solution, that no one (despite down voting) provided
char buf[SIZEBUFF]; sprintf(buf,"%s",float2send); sprintf(buf,"%ld",longInt2send);
int8_tin your array then shift right until you reach zero. This is is the easiest solution, but it puts the least significant bits first.