lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

Can anybody help me convert this 5.2 code to 5.3? I suck at binary stuff.

Original:

-- Author: Clark Li <clark.li86@gmail.com>
-- Ported from http://introcs.cs.princeton.edu/java/51data/CRC16CCITT.java.html-- Author: Clark Li <clark.li86@gmail.com>
-- Ported from http://introcs.cs.princeton.edu/java/51data/CRC16CCITT.java.html
local POLY = 0x1021
function ccitt_16(byte_array)

  local function hash(crc, byte)
    for i = 0, 7 do
      local bit = bit32.extract(byte, 7 - i) -- Take the lsb
      local msb = bit32.extract(crc, 15, 1) -- msb
      crc = bit32.lshift(crc, 1) -- Remove the lsb of crc
      if bit32.bxor(bit, msb) == 1 then crc = bit32.bxor(crc, POLY) end
    end
    return crc
  end

  local crc = 0xffff
  for i in ipairs(byte_array) do
    crc = hash(crc, byte_array[i])
  end

  return bit32.extract(crc, 0, 16)
end


My attempts to replicate bit32.extract yielded little worth posting:

local POLY = 0x1021
function ccitt_16_l(byte_array)

    local function hash(crc, byte)
        for i = 0, 7 do
            local bit = bit32.extract(byte, 7 - i) -- Take the lsb
            local msb = bit32.extract(crc, 15, 1) -- msb
            if (bit ~ msb) == 1 then
            crc = crc ~ POLY end
        end
        return crc
    end

    local crc = 0xffff
    for i in ipairs(byte_array) do
    crc = hash(crc, byte_array[i])
    end

    return crc & 0xffff
end

Part 2 to come...

Russ