gpt4 book ai didi

encoding - Lua,处理非ascii字节流,字节顺序改变

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

需要对字节流(可能包含非 ascii 字符)进行编码和解码,从/到 uint16、uint32、uint64(它们典型的 C/C++ 含义),并注意字节顺序。在 Lua 中做这样的事情有什么高效且有望跨平台的方式?

我的目标架构是 64 位 x86_64,但希望保持其可移植性(如果它不会在性能方面造成损失)。

例如

解码(比如当前在 Lua 字符串中)--0x00、0x1d、0xff、0x23、0x44、0x32(小端)作为 -uint16:(0x1d00)= 7424uint32:(0x324423ff)= 843326463

如果有人能用例子来解释那就太好了。

最佳答案

用于从字节转换为 int(处理字节级别的字节顺序和符号):

function bytes_to_int(str,endian,signed) -- use length of string to determine 8,16,32,64 bits
local t={str:byte(1,-1)}
if endian=="big" then --reverse bytes
local tt={}
for k=1,#t do
tt[#t-k+1]=t[k]
end
t=tt
end
local n=0
for k=1,#t do
n=n+t[k]*2^((k-1)*8)
end
if signed then
n = (n > 2^(#t*8-1) -1) and (n - 2^(#t*8)) or n -- if last bit set, negative.
end
return n
end

当我们这样做时,还有另一个方向:

function int_to_bytes(num,endian,signed)
if num<0 and not signed then num=-num print"warning, dropping sign from number converting to unsigned" end
local res={}
local n = math.ceil(select(2,math.frexp(num))/8) -- number of bytes to be used.
if signed and num < 0 then
num = num + 2^n
end
for k=n,1,-1 do -- 256 = 2^8 bits per char.
local mul=2^(8*(k-1))
res[k]=math.floor(num/mul)
num=num-res[k]*mul
end
assert(num==0)
if endian == "big" then
local t={}
for k=1,n do
t[k]=res[n-k+1]
end
res=t
end
return string.char(unpack(res))
end

欢迎任何评论,它已经过测试,但还不太彻底......

关于encoding - Lua,处理非ascii字节流,字节顺序改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5241799/

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