Reputation: 393
How can I copy data from an int (int port1 = 52010) to a pair of unsigned chars (unsigned char port2[2]
? I don't know how to deal with the division.
Upvotes: 1
Views: 206
Reputation: 1425
port2[0] = port1 >> 8;
port2[1] = port1 & 0x00FF;
or in reverse order depending on endianness
Upvotes: 2
Reputation: 399989
You typically use masking and shifting.
const unsigned short port = 52010;
uint8_t port2[2];
Big-endian:
port2[0] = port >> 8;
port2[1] = port & 255;
little-endian:
port2[0] = port & 255;
port2[1] = port >> 8;
For things like port numbers as used in IP networking, you typically always go to the so-called "network byte order" (aka "big-endian"), and there's a special macro for doing this:
const unsigned short port_n = ntohs(port);
Note that this keeps the port number as a unsigned short
, while swapping the bytes if necessary.
Upvotes: 5