简体   繁体   中英

how to convert a file containing hex format to binary format using lua

00004b0 ffff ffff ffff ffff ffff ffff ffff 00ff
00004c0 0000 fc01 ffff ffff ffff ffff ffff ffff
00004d0 ffff ffff 0089 0019 0801 0101 0000 0000
00004e0 0000 0000 0000 3130 0000 0009 ff02 00ff
00004f0 0000 0000 0000 ff00 ffff ffff ffff ffff
0000500 008b 001c 0a03 0001 0000 ffff ffff 94ff
0000510 b325 c55f 076f 000b ff02 acff ffa2 a733
0000520 fe19 28be 0000 ffff ffff ffff 008b 002a
0000530 0a05 0001 0000 001d df03 94e6 b325 c55f
0000540 076f 000b 0002 ac06 ffa2 a733 fe19 28be
0000550 0e00 0000 0000 0000 000b ff03 00ff 0000
0000560 0000 0000 ff00 ffff ffff ffff ffff 008b
0000570 002a 0a08 0001 0000 001d df03 94e6 b325
0000580 c55f 076f 000b 0002 ac09 ffa2 a733 fe19
0000590 28be 0e00 0000 0000 0000 000b ff03 00ff
00005a0 0000 b300 03b0 ff02 ffff ffff ffff ffff
00005b0 008b 002a 0a0b 0001 0000 001d df03 94e6
00005c0 b325 c55f 076f 000b 0002 ac0c ffa2 a733
00005d0 fe19 28be 0e00 0000 0000 0000 000b ff03
00005e0 00ff 0000 b300 03b0 ff02 ffff ffff ffff
00005f0 ffff ffff ffff ffff ffff ffff ffff ffff

I am actually having file like this how to convert into binary like 0x11 to 0001 0001

Here is an example of how to do it, using gmatch to select each byte in the string.

Then you convert the hex byte to it's number value and process that with a function to get the binary digits.

    local hexfile = '0011 ffff'

    local function bytetobin(n)
        local t = {}
        local d = 0

        d = math.log(65535) / math.log(2)

        for i = math.floor(d), 0, -1 do
            t[#t + 1] = math.floor(n / 2^i)
            n = n % 2^i
        end

        return table.concat(t)
    end

    local function hextobin(hex)
        local num = tonumber(hex, 16)            
        local bin = bytetobin(num)            
        local result = bin:gsub("()", {[5]=" ", [9]=" ", [13]=" "})

        return result
    end

    for line in hexfile:gmatch('([^\n]+)') do
        local binarystring = ''

        for v in line:gmatch("(%x+)") do
            binarystring = binarystring .. hextobin(v) .. ' '
        end

        print(binarystring)
    end

Output:

 0000 0000 0001 0001 1111 1111 1111 1111 

bytetobin function from: love2d user: Zorg modified to produce leading 0s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM