C语言实现对一串字符计算奇偶校验,计算Ruby中一个字节的奇偶校验位

你已经采取了看看RubyDES library?这可能不需要编写自己的实现。

计算奇偶校验,您可以使用类似以下内容:

require 'rubygems'

require 'inline' # RubyInline (install with `gem install RubyInline`)

class Fixnum

# native ruby version: simpler but slow

# algorithm from:

# http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel

def parity_native

(((self * 0x0101010101010101) & 0x8040201008040201) % 0x1FF) & 1

end

class << self

# inline c version using RubyInline to create c extension

# 4-5 times faster than native version

# use as class method:

# Fixnum.parity(0xAB)

inline :C do |builder|

builder.c <

int parity_c(int num) {

return (

((num * 0x0101010101010101ULL) & 0x8040201008040201ULL) % 0x1FF

) & 1;

}

EOC

end

end

def parity

self.class.parity_c(self)

end

def parity_odd?

1 == parity

end

def parity_even?

0 == parity

end

end

0xAB.parity # => 1

0xAB.parity_odd? # => true

0xAB.parity_even? # => false

(0xAB + 1).parity # => 0

根据简单的基准测试,内嵌C版是3-4倍,比天然红宝石版本

require 'benchmark'

n = 10000

Benchmark.bm do |x|

x.report("inline c") do

n.times do

(0..255).map{|num| num.parity}

end

end

x.report("native ruby") do

n.times do

(0..255).map{|num| num.parity_native}

end

end

end

# inline c 1.982326s

# native ruby 7.044330s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值