以二进制格式将数字写入lua文件 [英] Write numbers to a file in lua in binary format
本文介绍了以二进制格式将数字写入lua文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很大的数组,我想写一个文件。
I have a big array with numbers I would like to write to a file.
但如果我这样做:
local out = io.open("file.bin", "wb")
local i = 4324234
out:write(i)
我只是将数字作为字符串写入文件。如何为要归档的数字写入正确的字节。我怎么能在以后阅读它。
I am just writing the number as a string to the file. How do I write the correct bytes for the number to file. And how can I later read from it.
推荐答案
试试这个
function writebytes(f,x)
local b4=string.char(x%256) x=(x-x%256)/256
local b3=string.char(x%256) x=(x-x%256)/256
local b2=string.char(x%256) x=(x-x%256)/256
local b1=string.char(x%256) x=(x-x%256)/256
f:write(b1,b2,b3,b4)
end
writebytes(out,i)
还有这个
function bytes(x)
local b4=x%256 x=(x-x%256)/256
local b3=x%256 x=(x-x%256)/256
local b2=x%256 x=(x-x%256)/256
local b1=x%256 x=(x-x%256)/256
return string.char(b1,b2,b3,b4)
end
out:write(bytes(0x10203040))
这些工作用于32位整数,并首先输出最高有效字节。根据需要进行调整。
These work for 32-bit integers and output the most significant byte first. Adapt as needed.
这篇关于以二进制格式将数字写入lua文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文