极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 12741|回复: 2

发一个Ruby的代码

[复制链接]
发表于 2013-9-2 16:14:36 | 显示全部楼层 |阅读模式

这个代码用来计算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[0] = code[k].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"




回复

使用道具 举报

发表于 2013-9-3 12:22:06 | 显示全部楼层
表示不懂ruby,用不上.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-6-14 18:42:07 | 显示全部楼层
irb(main):007:0> '爱上Makeblock'.encode('gbk','utf-8').bytes.to_a
=> [176, 174, 201, 207, 77, 97, 107, 101, 98, 108, 111, 99, 107]
irb(main):008:0> '空'.encode('gbk','utf-8').bytes.to_a
=> [191, 213]
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-16 20:05 , Processed in 0.034100 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表