Luajit是否等效于string.pack和string.unpack? [英] Luajit equivalent for string.pack and string.unpack?

查看:164
本文介绍了Luajit是否等效于string.pack和string.unpack?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以字节形式保存lua float nuber列表,并将其附加到字符串.我知道Lua 5.3存在string.pack,但我仅限于Luajit.我对FFI不太熟悉,如果有解决方案,我会很感谢使用它的帮助(使用tostring(number)只会使用太多的数字字节,并且内存有限)

I need to save a list of lua float nubers in byte form and attach that to a string. I know string.pack exists for Lua 5.3 but I'm limited to Luajit. I'm not too familiar with FFI and I'd appreciate help on using it if it has a solution ( using tostring(number) just uses way too many bytes for numbers and memory is limited )

基本上,我需要一种方法来使用Luajit获取数字列表(现在为浮点数)的二进制字符串压缩形式,并将其存储在字符串&中.将那个字符串连接到另一个字符串,甚至在它之后写东西(我在5.3中遇到了麻烦,因此不确定在下面您向我建议的解决方案中是否有可能)

Basically, I need a way to get a binary string packed form of a list of numbers (floats for now), using Luajit, and be able to store it in a string & concat that string to another string and even write things after it (I got trouble with this one in 5.3, so not sure if it's possible in whatever solution you suggest to me below)

如果正确完成,是否有可能在获得的字符串上使用正则表达式?对我来说非常方便.

Also, if done correctly, is it possible that I use regex on the obtained string? it would be extremely handy for me.

主要由于性能,我不能使用lua 5.3作为替代.Luajit更快,更适合我正在用于(咳嗽训练神经网络)

I can't use lua 5.3 as an alternative mainly because of performance. Luajit is way faster and more suitable for the application I'm using it for (cough training neural networks)

当然,当我需要string.pack时,我需要string.unpack.

And of course, when I need string.pack, I need string.unpack.

推荐答案

如何将数字数组打包为二进制字符串:

How to pack array of numbers to a binary string:

-- convert t to str
local t = {1/3, 1/7, 3/5}  -- array of floating point numbers
local str = ffi.string(ffi.new("float[?]", #t, t), 4 * #t)

如何将二进制字符串解压缩为数字数组:

How to unpack binary string to array of numbers:

-- convert str to t
local ptr = ffi.cast("float*", ffi.new("char[?]", #str, str))
local t = {}
for _ = 1, #str / 4 do
   t[#t + 1] = ptr[#t]
end

对于8字节双打,将 float 替换为 double ,将 4 替换为 8

For 8-byte doubles, replace float with double and 4 with 8

这篇关于Luajit是否等效于string.pack和string.unpack?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆