这次测试需要建立很多数据文件(record)导入到数据库了。
导入的时候要求数字是内部的二进制形式,Ruby中没有像c一样处理以字节为单位的类型,把整数写到文件里,不小心就会变成字符串了,比如想写1,就会写进去一个1这个字符串(内部表示0×31),而不是写进去0×01。
有了这个bit-struct,就可以方便的处理这个问题了。
bit-struct是用string来存贮各种二进制数据,支持有无符号的整数,字符串,float等,应该足够用了。
这是一个例子:
- require 'bit-struct'
- class C < BitStruct
- signed :id, 32
- char :name,160
- signed :age,16
- unsigned :dept,16
- end
- File.delete("C:\\Program Files\\Crystal Point\\OutsideView32\\Upload\\aaa")
- f=open("C:\\Program Files\\Crystal Point\\OutsideView32\\Upload\\aaa","wb")
- 5.times do |i|
- c = C.new
- c.id = 2009 + i
- c.name = ((i % 10 ).to_s) *20
- c.age = -2 * i
- c.dept= 3 * i
- f.write(c)
- end
- f.close
底下的是一个例子用来读出文件的二进制数据并显示出来,类似UE,左边是16进制数据,右边是可打印字符串(没有处理tab,回车等特殊字符)
- row = 1
- buff = ""
- line_length = 16
- line_span = 0
- f = File.new("C:\\Program Files\\Crystal Point\\OutsideView32\\Upload\\aaa")
- until f.read( 16,buff )== nil
- print format("0x%04x : ",row)
- row = row + 1
- line_length = buff.length
- if line_length == 16
- line_span = 0
- else
- line_span = 16 - line_length
- end
- line_length.times do |c|
- print format("%02x ",buff[c])
- end
- line_span.times do
- print " "
- end
- print " #{buff[0..line_length -1]} \n"
- end
- f.close
这是上面程序的结果(有点变形):
0x0001 : 00 00 07 d9 30 30 30 30 30 30 30 30 30 30 30 30 ル000000000000
0x0002 : 30 30 30 30 30 30 30 30 00 00 00 00 00 00 07 da 00000000 レ
0x0003 : 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 1111111111111111
0x0004 : 31 31 31 31 ff fe 00 03 00 00 07 db 32 32 32 32 1111 ロ2222
0x0005 : 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 2222222222222222
0x0006 : ff fc 00 06 00 00 07 dc 33 33 33 33 33 33 33 33 ワ33333333
0x0007 : 33 33 33 33 33 33 33 33 33 33 33 33 ff fa 00 09 333333333333
0x0008 : 00 00 07 dd 34 34 34 34 34 34 34 34 34 34 34 34 ン444444444444
0x0009 : 34 34 34 34 34 34 34 34 ff f8 00 0c 44444444
bit-struct项目主页http://redshift.sourceforge.net/bit-struct/