Search code examples
cintunsigned-char

Copy data from int to 2 unsigned chars


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.


Solution

  • 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.