簡體   English   中英

如何使用 lua 將包含十六進制格式的文件轉換為二進制格式

[英]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

我實際上有這樣的文件如何轉換成二進制像 0x11 到 0001 0001

這是一個如何做到這一點的示例,使用gmatch到 select 字符串中的每個字節。

然后將十六進制字節轉換為它的數值並使用 function 進行處理以獲得二進制數字。

    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 來自: love2d 用戶:Zorg修改為產生前導 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM