-1

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?

1
  • You can just assign it to the next int8_t in your array then shift right until you reach zero. This is is the easiest solution, but it puts the least significant bits first. Commented Mar 22, 2016 at 11:29

2 Answers 2

0

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 :(

Sign up to request clarification or add additional context in comments.

15 Comments

Do you have any proof to suggest that on big systems those functions become no-op? Because I can't see any.
@Seb I don't know if a good compiler could completely optimise them away, but on a big-endian system ntohX(v) == v, i.e. it's the identity function.
This answer is wrong because you've confused "host byte order" with "host (whichever endian format that might be)". You think the 'h' part of htonl varies. It doesn't. Host byte order is always little endian.
So when you write 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.
@Seb you're absolutely wrong there - on most modern systems host order is little endian, but it's far from guaranteed. FWIW, network protocols are my speciality - when handling IETF binary protocols you should always use htonX when writing to the wire and ntohX when reading from the wire.
|
-2

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.