-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryReader.rb
125 lines (100 loc) · 2.41 KB
/
BinaryReader.rb
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# Google Search: how do I ruby read binary float
# Search Result 1
# From: Michael Neumann ([email protected])
# Subject: Re: Howto read binary data?
# View: Complete Thread (3 articles)
# Original Format
# Newsgroups: comp.lang.ruby
# Date: 2001-10-23 06:31:08 PST
BufferSize = 32768
#Martin Kahlert wrote:
#> Hi!
#> I want to read a file containing double values in binary representation,
#> i.e. they have been written from C using
#>
#> double variable;
#> write(fd, &variable, sizeof(variable));
#For this purpose, I wrote some time ago a class BinaryReader:
class BinaryReader
DEF = [
[ :Byte, 1, 'C' ], # or b or B : bug?
[ :Int16, 2, 's' ],
[ :UInt16, 2, 'S' ],
[ :Int32, 4, 'i' ],
[ :UInt32, 4, 'I' ],
[ :Float32, 4, 'f' ],
[ :Float64, 8, 'd' ]
]
DEF.each do |meth, size, format|
eval %{
def read#{ meth }(n = 1)
_read(n, #{size}, '#{ format }')
end
}
end
def readChar
@handle.readchar.chr
end
def readString(len=0)
string = ""
if len
len.times { | i | string += readChar }
else # len == 0 : read until null char found
string = handle.gets('\0')
end
string
end
def initialize( handle )
@handle = handle
end
private
def _read(n, size, format)
bytes = n * size
str = @handle.read(bytes)
raise "failure during read" if str.nil? or str.size != bytes
val = str.unpack(format * n)
if n == 1
val.first
else
val
end
end
end
#You can use this as follows:
#
#
# file = File.new(...)
# file.binary # only neccessary on Windows
# reader = BinaryReader.new( file )
#
# aFloat = reader.read_float
# int1, int2 = reader.read_int(2) # read two integers
# # ... read_double, read_ushort etc..
#
#Regards,
#
# Michael
#
#> How can i read this file from ruby and stuff the data into a ruby double
#> variable? (The file has been built on the same machine, so endianess should
#> not be a problem).
#
#See Array#pack and String#unpack.
#
#Regards,
#
# Michael
#--
#Michael Neumann
#merlin.zwo InfoDesign GmbH
#http://www.merlin-zwo.de
#
#
#
# Google Home - Advertise with Us - Business Solutions - Services & Tools -
# Jobs, Press, & Help
#
#©2003 Google
#
#
#