-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryFile.lua
56 lines (53 loc) · 1.25 KB
/
BinaryFile.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
local BinaryFile = {}
function BinaryFile.new_reader(filename)
local self = {}
self.file = io.open(filename, "rb")
if not self.file then
return nil
end
self.close = function ()
self.file:close()
end
-- utilizing luajit 2 bit module
self.u8 = function ()
return self.file:read(1):byte(1)
end
self.u16 = function ()
local a, b = self.file:read(2):byte(1, 2)
return bit.bor(a, bit.lshift(b, 8))
end
self.i32 = function ()
local a, b, c, d = self.file:read(4):byte(1, 4)
return bit.bor(a, bit.lshift(b, 8), bit.lshift(c, 16), bit.lshift(d, 24))
end
return self
end
function BinaryFile.new_writer(filename)
local self = {}
self.file = io.open(filename, "wb")
if not self.file then
return nil
end
self.close = function ()
self.file:close()
end
self.u8 = function (data)
self.file:write(string.char(data))
end
self.u16 = function (data)
self.file:write(string.char(
bit.band(data, 255),
bit.band(bit.rshift(data, 8), 255)
))
end
self.i32 = function (data)
self.file:write(string.char(
bit.band(data, 255),
bit.band(bit.rshift(data, 8), 255),
bit.band(bit.rshift(data, 16), 255),
bit.band(bit.rshift(data, 24), 255)
))
end
return self
end
return BinaryFile