John Jin
John Jin

Reputation: 21

Send an integer in two byte

I am going to transfer an integer number in two byte. As you know by using sprint function it splits your number into ASCII and sends them(for me by Ethernet connection). For Example:

sprintf(Buffer,"A%02ldB",Virtual);

My Virtual number is between 0 to 3600. By using sprintf function it sends ASCII codes(3600 converts to 4 ASCII bytes). However by converting 3600 to binary form we can see that we can squeeze it into a 12bit (or two bytes which bits between 13-16 are unused). But I can't send binary code again because sprintf sends ASCII codes for each 1 and 0. if I can convert my Virtual variable into two bytes I can increase my bytes transportation. So how can I convert a variable to two byte and them them by sprintf function?

Upvotes: 0

Views: 203

Answers (1)

grawity_u1686
grawity_u1686

Reputation: 16612

sprintf() doesn't do this, partly because it's specifically meant to work with strings (not binary data), and partly because there's nothing to convert – an integer variable in C already has bytes representing the number.

For example, if you have the variable declared as a short int or as uint16_t, that'll always hold your number in exactly two bytes, with &Virtual indicating the memory address where those bytes are kept, and I believe you can directly memcpy() the data into your network buffer. (Note: some types have a fixed size, others vary between architectures; be careful with those.)

The only thing you really should do before sending it is ensure that the bytes are in the correct order. That's another thing that varies between CPU architectures, so use htons()/htonl() to get an integer suitable for sending over the network, and upon receiving use ntohs()/ntohl() to convert it back to native CPU format.

Upvotes: 3

Related Questions