gpt4 book ai didi

lua - 将 Lua 字符串的前两个字节(bigendian 格式)转换为无符号短数

转载 作者:行者123 更新时间:2023-12-02 20:47:37 36 4
gpt4 key购买 nike

我想要一个带有字符串参数的 lua 函数。字符串有 N+2 字节的数据。前两个字节具有 bigendian 格式的长度,其余 N 个字节包含数据。

Say data is "abcd"
So the string is 0x00 0x04 a b c d

在 Lua 函数中,这个字符串是我的输入参数。如何计算长度最佳方式。

到目前为止我已经尝试过下面的代码

function calculate_length(s)
len = string.len(s)
if(len >= 2) then
first_byte = s:byte(1);
second_byte = s:byte(2);
//len = ((first_byte & 0xFF) << 8) or (second_byte & 0xFF)
len = second_byte
else
len = 0
end
return len
end

查看注释行(我在 C 中会如何做)。

在Lua中如何实现注释行。

最佳答案

字符串 s 中的数据字节数为 #s-2(假设即使没有数据的字符串也有两个字节的长度,每个字节都有一个值0)。如果您确实需要使用这些 header 字节,您可以计算:

len = first_byte * 256 + second_byte

当涉及到Lua中的字符串时,一个字节就是一个字节,如 this excerpt about strings引用手册中明确指出:

The type string represents immutable sequences of bytes. Lua is 8-bit clean: strings can contain any 8-bit value, including embedded zeros ('\0'). Lua is also encoding-agnostic; it makes no assumptions about the contents of a string.

如果使用string.*库,这一点很重要:

The string library assumes one-byte character encodings.

如果您的号码在 Lua 中的内部表示很重要,则以下 excerpt from the Lua Reference Manual可能感兴趣:

The type number uses two internal representations, or two subtypes, one called integer and the other called float. Lua has explicit rules about when each representation is used, but it also converts between them automatically as needed.... Therefore, the programmer may choose to mostly ignore the difference between integers and floats or to assume complete control over the representation of each number. Standard Lua uses 64-bit integers and double-precision (64-bit) floats, but you can also compile Lua so that it uses 32-bit integers and/or single-precision (32-bit) floats.

换句话来说,Lua 中不存在 2 字节“unsigned Short”C 数据类型。整数使用“long long”类型(8 字节有符号)存储。

最后,如lhf评论中指出,Lua中添加了按位运算in version 5.3 ,如果 lhf 是那个 lhf,他应该知道;-)

关于lua - 将 Lua 字符串的前两个字节(bigendian 格式)转换为无符号短数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672946/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com