#!/usr/local/bin/lua51 local bit = require("bit") local stdio = {} MAX_S8 = 2^7-1 MIN_S8 = -2^7 MAX_S16 = 2^15-1 MIN_S16 = -2^15 MAX_U8 = 2^8 MAX_U16 = 2^16 MAX_U32 = 2^32 stdio.writeu8 = function(dst, value) local b = bit.band(value, 0xff) dst:write(string.char(b)) end stdio.writes8 = function(dst, value) if value < 0 then value = MAX_U8 + value end stdio.writeu8(dst, value) end stdio.writeu16 = function(dst, value) local b2 = bit.band(bit.rshift(value, 8), 0xff) local b1 = bit.band(value, 0xff) dst:write(string.char(b1, b2)) -- Little Endian x86 end stdio.writes16 = function(dst, value) if value < 0 then value = MAX_U16 + value end stdio.writeu16(dst, value) end stdio.writeu32 = function(dst, value) local b4 = bit.band(bit.rshift(value, 24), 0xff) local b3 = bit.band(bit.rshift(value, 16), 0xff) local b2 = bit.band(bit.rshift(value, 8), 0xff) local b1 = bit.band(value, 0xff) dst:write(string.char(b1, b2, b3, b4)) -- Little Endian x86 end stdio.writes32 = function(dst, value) if value < 0 then value = MAX_U32 + value end stdio.writeu32(dst, value) end return stdio