luabcd

How convert BCD format to integer in Lua


I need to write a LUA script that can convert a number from a BCD format to an integer. Let's say my initial byte array looks like this:

local bcdArray = {0x73, 0x31, 0x30, 0x00}

If I understand the BCD format correctly, this array should turn into 31337. I have never worked with this programming language before, please help.


Solution

  • Here is one solution, avoiding bit logic to support every Lua version.

    local bcdArray = {0x73, 0x31, 0x30, 0x00}
    
    local result = 0
    for i, b in ipairs(bcdArray) do
        -- Every b encodes 2 decimals
        local b1 = b % 16 -- thus we split them into lower half
        local b2 = math.floor(b / 16) -- and upper half
        
        -- and add both to the result by setting the digit at position i * 2 - 1 and 2 respectively
        result = result + b1 * 10 ^ (i * 2 - 1) + b2 * 10 ^ (i * 2 - 2)
    end
    
    print(result)
    

    Keep the maximum integer size in mind!