Thought's on my Binary to Decimal Script?

local Base2 = {
	[0] = 1,
	[1] = 2,
	[2] = 4,
	[3] = 8,
	[4] = 16,
	[5] = 32,
	[6] = 64,
	[7] = 128,
}

local Encoded = 0

function Decode(Byte: string)
	local Bits = {
		[1] = "0",
		[2] = "0",
		[3] = "0",
		[4] = "0",
		[5] = "0",
		[6] = "0",
		[7] = "0",
		[8] = "0"
	}
	
	for i = 1, Byte:len() do
		local Bit = Byte:reverse():sub( i , i )

		Bits[i] = Bit
	end
	
	for i = 1, #Bits do
		Encoded = Encoded + ( Binary.Base2[ i - 1 ] * tonumber(Bits[i], 10))
	end

	return Encoded
end

This works perfectly well though I want to take some feedback from the community if my script is well optimized, and get some certain advice. All though, this can only decode up to a byte of information.

2 Likes

You know tonumber() can convert binary strings (or a string representation of a number of any base) to decimals, right?

print(tonumber("0100010", 2)) -- 34
1 Like

Well I tried challenging myself to try creating one myself cause binary numbers are so impressing to me.

1 Like

Just pointing out that you didn’t need a lookup table since base2 is 2^n

2 Likes

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