Lua(5.0)中与Python struct.pack相当的函数。

我正在尝试将一些 Python 代码转换为 Lua。Lua 的等效方法是什么:

value2 = ''
key = 'cmpg'
value1 = '\x00\x00\x00\x00\x00\x00\x00\x01'
Value2 += '%s%s%s' % (key, struct.pack('>i', len(value1)), value1)

原文链接 https://stackoverflow.com/questions/9746368

点赞
stackoverflow用户84270
stackoverflow用户84270

你在评论中说:

我可能可以只知道以下每个字符串生成:struct.pack('> i',4),struct.pack('> i',8)和struct.pack('> i',10)

'>'i 的作用是 bigendian signed 32-bit integer。对于非负输入 x,简单的 Python 等效代码将是

chr(( x >> 24) & 255) + chr(( x >> 16) & 255) + chr(( x >> 8) & 255) + chr( x & 255)

你应该可以轻松地在 Lua 中表示这个代码。

你在另一个评论中说:

我...不明白一个答案(@john machin)

chr(x) 很容易在文档中找到。Lua 应该有这样的函数,可能甚至同名。

'i >> n' 将 i 向右移动 n 位。如果 i 是无符号的,则相当于 i // (2 ** n),其中 // 是 Python 的整数 floor division。

'i & 255' 是按位与,相当于 i % 256

Lua 应该都有这些。

这种情况下的 '+' 是字符串连接。

看看这个:

>>> import binascii
>>> def pack_be_I(x):
...     return (
...         chr((x >> 24) & 255) +
...         chr((x >> 16) & 255) +
...         chr((x >>  8) & 255) +
...         chr(x         & 255)
...         )
...
>>> for anint in (4, 8, 10, 0x01020304, 0x04030201):
...     packed = pack_be_I(anint)
...     hexbytes = binascii.hexlify(packed)
...     print anint, repr(packed), hexbytes
...
4 '\x00\x00\x00\x04' 00000004
8 '\x00\x00\x00\x08' 00000008
10 '\x00\x00\x00\n' 0000000a
16909060 '\x01\x02\x03\x04' 01020304
67305985 '\x04\x03\x02\x01' 04030201
>>>

你会注意到 10 所需的输出是 '\x00\x00\x00\n'... 注意 '\x0a''\n'chr(10) 需要注意。如果你要将这些东西写入 Windows 上的文件,则必须以二进制模式( 'wb',而不是 'w')打开文件,否则运行时库将插入回车字节,以符合 Windows、MS-DOS、CP/M 对文本文件的约定。

2012-03-17 05:13:32
stackoverflow用户837856
stackoverflow用户837856

请查看string.pack; 你可以在 Lua for Windows 内找到预编译的Windows二进制文件。

value2 = ''
key = 'cmpg'
value1 = '\x00\x00\x00\x00\x00\x00\x00\x01'
value2 = string.format("%s%s%s", key, string.pack(">i", #value1, value))

如果你正在使用 LuaJIT (我强烈推荐的), 你可以使用FFI并将原始值转换为字节数组并使用memcpy。

2012-03-17 09:59:32
stackoverflow用户4279
stackoverflow用户4279

Read Write Format Wiki 页面包含了一些函数,用于将整数值打包/解包为二进制字符串。

示例

-- 使用 width 字节以 MSB 格式写入整数。
function numbertobytes(num, width)
  local function _n2b(t, width, num, rem)
    if width == 0 then return table.concat(t) end
    table.insert(t, 1, string.char(rem * 256))
    return _n2b(t, width-1, math.modf(num/256))
  end
  return _n2b({}, width, math.modf(num/256))
end

io.write("<", numbertobytes(0x61626364, 4), ">\n")

输出

<abcd>
2012-03-17 11:54:52
stackoverflow用户221509
stackoverflow用户221509

怎么样使用 struct.pack 来为 Lua 编写程序(它基于 string.pack 的代码)?它提供了您期望的相同的功能。因此,您可以运行以下代码:

local key = 'cmpg'
local value1 = '\0\0\0\0\0\1'
local packed = key .. struct.pack('>i', #value1) .. value1

或者,查看文档中的示例,也可以像这样做:

local packed = key .. struct.pack('>ic0', #value1, value1)

要解包这样的字符串,请使用以下方法(假设您在 data 中只有 <length,string>):

local unpacked = struct.unpack('>ic0', data)
2012-03-18 08:59:27