最近在寫 Lua 腳本,需要讀取二進(jìn)制文件并轉(zhuǎn)化為十六進(jìn)制的字符串,C語言讀文件,返回的是字符串類型,Lua 返回的也是字符串類型(用的時候忘記去查類型了,導(dǎo)致這個地方浪費了很長的時間。。。),由于找解決方法找了蠻長時間的,所有在這里先記錄一下。
local function readAll(filePath)
--
local f = assert(io.open(filePath, "rb"))
local content = f:read("*all")
f:close()
return content
end
local function bytesToHexStr(filePath)
--
local content = readAll(filePath)
local result = ""
local len = string.len(content)
for i = 1, len do
local charcode = tonumber(string.byte(content, i, i));
local hexstr = string.format("%02X", charcode);
result = result .. hexstr
end
return result
end
有一個小問題,順便記錄一下,在讀取了二進(jìn)制文件后,本想用print打印看看內(nèi)容有沒有被讀出來,結(jié)果只打印了一部分,用 notepad++ 打開發(fā)現(xiàn),文件有很多 NUL 的字符,原因是 print 在遇到 NUL 就結(jié)束打印了,囧o(╯□╰)o
十六進(jìn)制轉(zhuǎn)二進(jìn)制可以參考這個:Lua小程序:十六進(jìn)制字符串和二進(jìn)制數(shù)據(jù)間的轉(zhuǎn)換
