バイナリファイルを作る

ひさしぶりにLuaをやる。
Luaでバイナリファイルを作る。例としてUDPヘッダを作ってみた。

#!/bin/env lua
require("bit")

src_port=3088
dst_port=333
length=1200
crc=0xABCD

function write_word(f, word)
    if word > 0xff then
        f:write(string.format("%c%c", bit.band(word, 0x00ff), bit.rshift(bit.band(word, 0xff00),8)))
    else
        f:write(string.format("%c", bit.band(word, 0x00ff)))
        f:write("\0")
    end
end

f=io.open("udph.bin", "wb")
write_word(f, src_port)
write_word(f, dst_port)
write_word(f, length)
write_word(f, crc)
f:close()
$ lua make_udp_header.lua ;hexdump udph.bin
0000000 0c10 0016 04b0 abcd
0000008

string.formatの%cは0が入力されると、何も出力されないようです。
すごく無理やりな感じです。もっと良い方法がありそうな気がします。

参考:Programming in Lua : 21.2.2 Binary Files