2024-09-30 05:22:29 发布
网友
我正在尝试将一些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)
请看一下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。在
对Lua使用^{}怎么样(它基于string.pack的代码)?它提供了您所期望的相同功能。因此,您可以运行以下代码:
string.pack
local key = 'cmpg' local value1 = '\0\0\0\0\0\1' local packed = key .. struct.pack('>i', #value1) .. value1
或者,看看文档中的示例,您也可以这样做:
要解压缩这样的字符串,请使用以下命令(假设您在data中只有<length,string>):
data
<length,string>
local unpacked = struct.unpack('>ic0', data)
你在评论中说:
I may be able to get by with knowing the string generated by each of the following: struct.pack('>i',4),struct.pack('>i',8), and struct.pack('>i',10)
效应器“>;i”表示bigendian有符号32位整数。对于非负输入x,简单的Python等价物是
chr((x >> 24) & 255) + chr((x >> 16) & 255) + chr((x >> 8) & 255) + chr(x & 255)
你应该能够在Lua中毫不费力地表达出来。在
你在另一条评论中说:
I ... don't understand an answer (@john machin)
chr(x)很容易在文档中找到。Lua应该有这样一个函数,甚至可能同名。在
i >> n将i右移n位。如果i是无符号的,这相当于i // ( 2 ** n),其中//是Python的整数楼层除法。在
i >> n
i // ( 2 ** n)
//
i & 255是位的,它等价于i % 256。在
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'aka'\n'akachr(10)需要护理。如果要将这些内容写入Windows上的文件中,则必须以二进制模式('wb',而不是'w')打开该文件,否则运行时库将插入回车字节,以符合Windows、MS-DOS、CP/M文本文件约定。在
10
'\x00\x00\x00\n'
'\x0a'
'\n'
chr(10)
'wb'
'w'
请看一下string.pack;您可以在Lua for Windows中找到Windows的预编译二进制文件。在
如果您使用的是LuaJIT(我强烈推荐),那么可以使用FFI并将原始值转换为字节数组并使用memcpy。在
对Lua使用^{} 怎么样(它基于
string.pack
的代码)?它提供了您所期望的相同功能。因此,您可以运行以下代码:或者,看看文档中的示例,您也可以这样做:
^{2}$要解压缩这样的字符串,请使用以下命令(假设您在
data
中只有<length,string>
):你在评论中说:
效应器“>;i”表示bigendian有符号32位整数。对于非负输入x,简单的Python等价物是
chr((x >> 24) & 255) + chr((x >> 16) & 255) + chr((x >> 8) & 255) + chr(x & 255)
你应该能够在Lua中毫不费力地表达出来。在
你在另一条评论中说:
chr(x)很容易在文档中找到。Lua应该有这样一个函数,甚至可能同名。在
i >> n
将i右移n位。如果i是无符号的,这相当于i // ( 2 ** n)
,其中//
是Python的整数楼层除法。在i & 255
是位的,它等价于i % 256
。在Lua应该有这两样东西。在
在本例中,
+
是字符串连接。在看看这个:
您会注意到
10
所需的输出是'\x00\x00\x00\n'
。。。请注意,'\x0a'
aka'\n'
akachr(10)
需要护理。如果要将这些内容写入Windows上的文件中,则必须以二进制模式('wb'
,而不是'w'
)打开该文件,否则运行时库将插入回车字节,以符合Windows、MS-DOS、CP/M文本文件约定。在相关问题 更多 >
编程相关推荐