Hacker News new | ask | show | jobs
by Joker_vD 1833 days ago
> It is as simple as dumping struct ntp_packet on wire and reading it off it -- no parsing involved except for calling ntohX()/htonX() on all fields except li, vn and mode.

Nope, you may still need to call ntoh/hton, depending on how the compiler you use orders the bitfields inside an int. Plus you need "__attribute__((packed))" or whatever the compiler you use supports to make that C struct definition mean what it looks like it means: even then I am not sure those three bitfields are required to occupy exactly 8 bits.

1 comments

Better yet is using wrappers for char arrays paired with helper functions:

    typedef struct { unsigned char data[2]; } u16be_t;

    inline static uint16_t get_u16be(const u16be_t *p) {
        uint16_t result = 0;
        result |= (uint16_t) p->data[0] << 8;
        result |= (uint16_t) p->data[1];
        return result;
    }

    inline static void put_u16be(u16be_t *p, uint16_t value) {
        p->data[0] = value >> 8;
        p->data[1] = value;
    }
Perfectly portable (as long as CHAR_BIT = 8), type-safe, and on modern compilers it generates no overhead over direct memory accesses.