Namaran

Code daily. Without assist.

2026-10-05

packet.c

#include <stdint.h>
#include <stdio.h>
#include <string.h>

union word {
    unsigned char bytes[4];
    uint32_t value;
};

static uint32_t read_length(const unsigned char *packet) {
    union word w;
    memcpy(w.bytes, packet, 4);
    return w.value;
}

int main(void) {
    const unsigned char packet[] = { 0x00, 0x00, 0x01, 0x2C, 'h', 'i' };
    printf("%lu\n", (unsigned long)read_length(packet));
}

read_length は、パケットの先頭4バイトに上位バイトから順に(ビッグエンディアンで)入っている長さを読むつもりの関数です。引数も標準入力も使わず、パケットの先頭4バイトは 00 00 01 2C です。x86-64 の機械で動かすと、いまは 738263040 が出ます。本来は 300 が出るはずです。

Answer

Wrong

static uint32_t read_length(const unsigned char *packet) {
    union word w;
    memcpy(w.bytes, packet, 4);
    return w.value;
}

w.bytes に写した4バイトを w.value から読むと、その4バイトは、この機械が uint32_t を記憶域に置く順序で解釈されます。x86-64 は下位のバイトを先頭に置くリトルエンディアンなので、00 00 01 2C は 0x2C010000、つまり 738263040 として読まれます。

共用体による読み替えは、処理系のバイト順をそのまま持ち込むだけで、パケットがどのバイト順で書かれているかは見ていません。上位バイトを先頭に置くビッグエンディアンの機械でだけ、たまたま 300 になります。

Right

static uint32_t read_length(const unsigned char *packet) {
    return (uint32_t)packet[0] << 24 | (uint32_t)packet[1] << 16
         | (uint32_t)packet[2] << 8 | packet[3];
}

シフトと論理和は記憶域の並びではなく値に対する演算なので、packet[0] を最上位の8ビットに置く、という意味がどの機械でも変わりません。バイト順を決めるのが機械ではなくコードになり、0x0000012C の 300 が返ります1。

(uint32_t) のキャストも外せません。unsigned char は演算の前に int へ昇格するので、キャストなしの packet[0] << 24 は int のシフトになり、packet[0] が 0x80 以上だと結果が int で表せず、未定義動作になります。

  1. POSIX の ntohl も同じ目的の関数ですが、C の標準ライブラリにはありません。C23 の <stdbit.h> には処理系のバイト順を表す __STDC_ENDIAN_NATIVE__ が加わりましたが、バイト順を調べて分岐するより、シフトで組み立てるほうが短く書けます。