Ruby 语言 思想驱动生活

June 16, 2007

用bit-struct处理结构化(二进制)数据

Filed under: Ruby — liubin @ 19:59

这次测试需要建立很多数据文件(record)导入到数据库了。
导入的时候要求数字是内部的二进制形式,Ruby中没有像c一样处理以字节为单位的类型,把整数写到文件里,不小心就会变成字符串了,比如想写1,就会写进去一个1这个字符串(内部表示0×31),而不是写进去0×01。
有了这个bit-struct,就可以方便的处理这个问题了。
bit-struct是用string来存贮各种二进制数据,支持有无符号的整数,字符串,float等,应该足够用了。

这是一个例子:

  1. require 'bit-struct'
  2.  
  3. class C < BitStruct
  4.   signed      :id, 32
  5.   char        :name,160
  6.   signed      :age,16
  7.   unsigned    :dept,16
  8. end
  9.  
  10. File.delete("C:\\Program Files\\Crystal Point\\OutsideView32\\Upload\\aaa")
  11. f=open("C:\\Program Files\\Crystal Point\\OutsideView32\\Upload\\aaa","wb")
  12.  
  13. 5.times do |i|
  14.  
  15.   c = C.new
  16.   c.id = 2009 + i
  17.   c.name = ((i % 10 ).to_s) *20
  18.   c.age = -2 * i
  19.   c.dept= 3 * i
  20.   f.write(c)
  21. end
  22.  
  23. f.close


底下的是一个例子用来读出文件的二进制数据并显示出来,类似UE,左边是16进制数据,右边是可打印字符串(没有处理tab,回车等特殊字符)

  1. row = 1
  2. buff = ""
  3. line_length = 16
  4. line_span = 0
  5.  
  6. f = File.new("C:\\Program Files\\Crystal Point\\OutsideView32\\Upload\\aaa")
  7.  
  8. until f.read( 16,buff )== nil
  9.   print format("0x%04x : ",row)
  10.   row = row + 1
  11.   line_length = buff.length
  12.   if line_length == 16 
  13.     line_span = 0
  14.   else
  15.     line_span = 16 - line_length 
  16.   end
  17.   line_length.times do |c|
  18.      print format("%02x ",buff[c])
  19.   end
  20.   line_span.times do
  21.      print "   "
  22.   end
  23.   print "   #{buff[0..line_length -1]} \n" 
  24. end
  25. 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/

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.

Powered by WordPress