Encode/Decode Hex?

Hello, I am trying to encode/decode hex strings just like in NodeJS with “Buffer”. Is there a way to do that?

1 Like

there are a couple things to keep in mind here

I’m guessing you want to be able to turn a hex string into a decimal string and a decimal string into a hex string

Encode

to turn a decimal string into a hex string we first need to understand ASCII code
now that we understand ASCII code you need to convert every single character into its ASCII code

let’s convert “(2<” to ASCII code, now the string is “40 50 60"
now that we converted it to ASCII code we just need to convert each number to hex
now that we converted them to hex it should look like this “28 32 3C”, there we encoded it

Decode

to turn hex string into a decimal string we need to get out our encoded string which was “28 32 3C”
now that we have the hex string we need to convert the hex numbers into decimal numbers
now that we converted them to decimal numbers we have “40 50 60” again
now all we have to do is think that those numbers are ASCII code and use this hyper link to convert it back to decimal string
now it should look like “(2<”, there we decoded it

sorry if this sounds a bit complicated but I tried to explain it in a lot of detail :sweat_smile:

2 Likes

Yes:

function fromHex(str)
	return (str:gsub('..', function (cc)
		return string.char(tonumber(cc, 16))
	end))
end

function toHex(str)
	return (str:gsub('.', function (c)
		return string.format('%02X', string.byte(c))
	end))
end

Modified from this gist to not error (because the string “class” is a readonly table):

example:

print(toHex("Test"))
print(fromHex("54657374"))

7ewfem_92791

7 Likes

Thank you, sounds a bit complicated, not gonna lie :sweat_smile:

It is you again!! And thank you it works!

yea I think @steven4547466 did a better job at how to do it on lua, I mainly explained how to do it in general

steven’s code basically does what I said but using lua functions to make it smaller and more compact

2 Likes