简体   繁体   中英

Sending two bytes in C with TCP

I wonder if there is any trips or falls concerning sending two byes as a whole or a byte array.

Say I want to send uint16_t . Is it better to send array of two bytes like uint8_t[2] or just send 16 bits at a time?

The main thing you need to keep in mind is endianness . That is, the order the bytes are interpreted in is different on different platforms.

For example, your Intel CPU might interpret the byte string 0x01 0x00 to be the number 1, but someone else's PowerPC would interpret that string of bytes to be the number 256.

When building a network protocol, it's important to keep issues like this in mind. (you might look at something like Google Protocol Buffers , which was designed to address this concern)

Since you're only talking about two bytes, you should also take a look at the htons() macro. This converts a 2-byte value from host order to network order . (network order is big endian , whereas host order is often little endian , but on big endian platforms htons() can simply be defined as a no-op.) If you want to send 4-byte (32-bit) values, you should also take a look at the htonl() macro. htons stands for host to network short , and will convert your 16-byte value to an equivalent network order 16-bit value (if you are on an Intel CPU, that means it will return a version of the 16-bit integer with the bytes swapped). When you have incoming bytes, your code should use the ntohs (and ntohl , for 32-bit values) macro to convert the incoming data from network byte order back to host order.

Also, you'd obviously want to send both bytes using a single socket write operation. Don't write one byte and then write the other using two writes as that could end up being very inefficient over the wire. That is, don't write uint8_t[0] followed by uint8_t[1]. Writing &uint16_t will avoid that situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM