szpapas 发表于 2013-9-2 16:14:36

发一个Ruby的代码


这个代码用来计算CRC16,HEX 文本格式 和数值之间转换。在Class String上做扩展,方便使用。

其它就不多说了,需要的拿去用。

class String
def crc16
    crcnum=0xFFFF
    self.each_byte do |b|
   crcnum=crcnum^((b.to_i)&0x00ff)
   1.upto(8) do
      if (crcnum&0x0001)!=0 then
       crcnum=(crcnum>>1)^0x8408
      else
       crcnum=crcnum>>1
      end
   end
    end
    crcnum
    sprintf("%02X %02X", crcnum & 0xFF, crcnum >> 8)
end

def hex2str
    str = ''
    self.each_byte do |b|
      str = str +sprintf("%02X", b) + ' '
    end
    str
end

def str2hex
    ss, chr = "", "\000"
    code = self.split(" ")
    for k in 0..code.size-1
      chr = code.to_i(16)
      ss = ss + chr
    end
    ss
end
   
end

例子:

>> "11 00 EE 00 E2 00 34 11 B8 02 01 16 05 26 17 08".str2hex.crc16
=> "8D 0A"

>> "11 00 EE 00 E2 00 34 11 B8 02 01 16 05 26 17 08 8D 0A".str2hex.crc16
=> "00 00"




chzhewl 发表于 2013-9-3 12:22:06

表示不懂ruby,用不上.

szpapas 发表于 2015-6-14 18:42:07

irb(main):007:0> '爱上Makeblock'.encode('gbk','utf-8').bytes.to_a
=>
irb(main):008:0> '空'.encode('gbk','utf-8').bytes.to_a
=>
页: [1]
查看完整版本: 发一个Ruby的代码