Reputation: 737
i have the following hex C0010203 i need to store it in bytes in a bytes table
i forgot the syntax i remember
bytes={}
bytes={0xC0 , something here}
or
bytes = {something here, 0xC0}
thanks for the help
Upvotes: 0
Views: 3857
Reputation: 2753
In Lua there is no "byte table". There is, however, a table with the bytes as numbers.
bytes={0xC0, 0x01, 0x02, 0x03}
And here are some other options:
--A table with the bytes as numbers in little-endian:
bytes={0x03, 0x02, 0x01, 0xC0}
--A string of characters that contain the bytes:
bytes=string.char(0xC0, 0x01, 0x02, 0x03)
--A string of characters that contain the bytes in little-endian:
bytes=string.char(0x03, 0x02, 0x01, 0xC0)
--A table of single character strings for each byte:
bytes={string.char(0xC0),string.char(0x01),string.char(0x02),string.char(0x02)}
--A table of single character strings for each byte in little-endian:
bytes={string.char(0x03),string.char(0x02),string.char(0x01),string.char(0xC0)}
Upvotes: 0
Reputation: 9549
My throw at this would be:
s="C001020304"
t={}
for k in s:gmatch"(%x%x)" do
table.insert(t,tonumber(k,16))
end
Upvotes: 1
Reputation:
It's a bit unclear to me what you mean, something like this?
tomte@tomte ~ $ lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> bytes={}
> bytes["something here"]=0xC0
> print(bytes["something here"])
192
>
EDIT: I see, possibly crude but working solution (without bounds checking, you have to adjust the code for strings that don't have an even length or don't contain hex-numbers);
tomte@tomte ~ $ lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> i=1
> j=1
> t={}
> s="C0010203"
> while true do
>> t[j] = 0 + ("0x" .. string.sub(s,i,i+1))
>> j=j+1
>> i=i+2
>> if(i>string.len(s)) then break end
>> end
> print (t[1])
192
> print (t[2])
1
> print (t[3])
2
> print (t[4])
3
Upvotes: 0