String.byte not working

so I was trying to make a String to Bytes and Bytes to String script thing, but i’ve found some problem.

when do the String.byte using “Rawr”, it just take the “R” instead of all text, so the returned byte is 82, I want them to be 82 97 119 114.

str is a string
local Length = str:len()
local Byte = string.byte(str, 1, Length)
print(str, Length, Byte)
return Byte

so if you know whats wrong, please help!

local ToByte = function(String)
	local FinishedString = ""
	
	for i = 1, string.len(String) do 
		FinishedString..=string.byte(String, i, string.len(String)).." "
	end
	
	return FinishedString
end

print(ToByte("Rawr")) -->> 82 97 119 114 

The problem you are having is brought on by the fact that the string.byte function only returns the ASCII value of the string’s first character. You must iterate over each character and obtain the ASCII value separately if you want to obtain the ASCII values of every character in the string.

Here is an example of how you can do this:

local str = "Rawr"
local bytes = {}

for i = 1, str:len() do
  local char = str:sub(i, i)
  local byte = string.byte(char)
  table.insert(bytes, byte)
end

print(str, bytes) -- "Rawr", {82, 97, 119, 114}

The string.byte method is used in this code to cycle through the characters in the str string and get their ASCII values. The ASCII values are then kept in a table called bytes.

The string can then be converted back to bytes using the string.char function by using this table of ASCII values. Here is an illustration of how to accomplish it:

local str = ""

for i, byte in ipairs(bytes) do
  str = str .. string.char(byte)
end

print(str, bytes) -- "Rawr", {82, 97, 119, 114}

Using the string.char function, this code loops through the bytes table and changes each ASCII value back to a character. After that, it joins all the characters to create the original string.

I hope this is useful. If you have any further inquiries, please let me know.

2 Likes

Woah youre right, it works now. your code with czo are same, but i will make your reply as the solution since you have the explanation! thanks!!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.