Split a table and send the Hex key

Viewed 69

I am tryin to convert a table I have with a limit of 16 characters to hex keys and then store those hex keys in another table in the same order as the original string.

I have found a function using some online help which can take a string, split it into each character and assign that character to a space in a table.

So if I write function("Hello World!") the return of the function would be table= {H, e, l, l, o, , W, o, r, l, d, !)

Now I need to limit this to only accept 16 characters and any more than that are discarded.

The function goes as

local str = "Hello World"
local chars = {}

for c in string.gmatch(str, ".") do
chars[#chars+1] = c
end

How can I limit this to 16 elements in the table?

My second question would be after I create this table, how do I go about changing each element of this table to a hex key and storing it in another table in the same order as the original string?

EDIT1: Thank you luke10000 for suggesting the if char.. method, it works perfectly. Now the next part is to convert this to hex and place it in a table. I found a function which does this operation but there was no explanation with it at all, I understand some of it but not all. I can only print with this to the console all the hex keys.

   function hex_dump(buf)
  for byte=1, #buf, 16 do
     local chunk = buf:sub(byte, byte+15)
     --io.write(string.format('%08X  ',byte-1)) -- 0's
     chunk:gsub('.', function (c) io.write(string.format('0x%X ',string.byte(c))) end)
     io.write(string.rep(' ',3*(16-#chunk)),"\n")
     --io.write(' ',chunk:gsub('%c','.'),"\n")  -- add the character infront of hex key
  end end

for _, chars in ipairs(chars) do


hex_dump(chars) end
1 Answers

I'm not sure how the rest of your post is related to your actual problem.

I am tryin to convert a table I have with a limit of 16 characters to hex keys and then store those hex keys in another table in the same order as the original string.

I'm also not sure what you mean with "hex key".

local input = {"H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"}
local output = {}    
for i,v in ipairs(input) do
  output[i] = string.format("0x%X", v:byte())
  if i == 16 then break end
end
print(table.concat(output, ", "))

Regarding your other questions:

local str = "Hello World"
local chars = {}

for c in string.gmatch(str, ".") do
chars[#chars+1] = c
end

How can I limit this to 16 elements in the table?

Simply limit your input string to 16 characters.

for c in str:sub(1,16):gmatch(".") do ...

My second question would be after I create this table, how do I go about changing each element of this table to a hex key and storing it in another table in the same order as the original string?

If your actual problem is to get a table of number representations from a string, simply use string.byte

local str = "Hello world! This is a wonderful day.!"
local output = table.pack(str:byte(1, 16))
Related