c - 如何将 CRC 函数从 C 转换为 Ruby?

标签 c ruby

我正在尝试将以下 C 函数转换为 Ruby,但无法弄清楚我做错了什么。我感觉它与数据类型有关,特别是在将它们传递给 Ruby 函数时,但无法查明确切的错误。

这是我的 C 代码:

#include <stdio.h>
#include <stdint.h>
uint32_t btle_calc_crc(uint32_t crc_init, uint8_t *data, int len) {
    uint32_t state = crc_init;
    uint32_t lfsr_mask = 0x5a6000; // 010110100110000000000000
    int i, j;
    for (i = 0; i < len; ++i) {
        uint8_t cur = data[i];
        for (j = 0; j < 8; ++j) {
            int next_bit = (state ^ cur) & 1;
            cur >>= 1;
            state >>= 1;
            if (next_bit) {
                state |= 1 << 23;
                state ^= lfsr_mask;
            }
        }
    }  
    return state;
}
int main(){
  uint32_t crc_init = 0x55555555;
  uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
    uint32_t crc = btle_calc_crc(crc_init, data, sizeof(data));
    printf("crc: %i\n", crc);
}

这是我的 Ruby 版本:

def calculate_crc(crc_init, data)
    lfsr_mask = 0x5a6000
    state = crc_init
    data.each do |byte|
        cur = byte
        (0..7).each do |i|
            next_bit = (state ^ cur) & 1;
            cur = (cur >> 1) && 0xff  # only 8 bit
            state = state >> 1
            if(next_bit == 1) 
                state = state | 1 << 23
                state = state ^ lfsr_mask
            end
        end
    end
    return(state)
end
crc = calculate_crc(0x555555, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06])
puts "crc: #{crc}"

最佳答案

您的 crc_init 似乎使用了不同的值; C 版本是 0x55555555(8 个 5),Ruby 版本是 0x555555(6 个 5)。你应该先纠正这个问题。

此外,我怀疑您需要在此行中使用 & 而不是 &&:

cur = (cur >> 1) && 0xff  # only 8 bit

关于c - 如何将 CRC 函数从 C 转换为 Ruby?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18562995/

相关文章:

创建 C 可执行文件来运行安装程序

ruby - 为什么我的正则表达式回溯在使用 Ruby 1.9 的 URL 上不起作用?

ruby-on-rails - rake db migrate 的版本是什么

C 关于指针内存分配的混淆?

c - 随机函数卡在一个数字上

c - 对已安装 APR C 库的 undefined reference

ruby-on-rails - rake 数据库 :migration aborted

c - 使用 mbedlts 在内存受限的系统上使用 SHA 散列文件

单引号或双引号字符串的 ruby​​ 编码约定

ruby-on-rails - Rails Ruby 优点 gem 观察器不起作用