This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
AndreWalia's profile picture

Help Decoding Binary

Started by AndreWalia, 08 September 2013 - 06:09 PM
AndreWalia #1
Posted 08 September 2013 - 08:09 PM
I am trying to make a binary decoder in which you would enter a number in binary, and you would get that number back in decimal, though for some reason no matter what I enter, it returns 0.


term.clear()
term.setCursorPos(1,2)
write("Binary number: ")
local binary = io.read()
local function getDecimal(place,code)
  local a = 1
  for i = 1,place do
	local a = a*2
	print(a)
  end
  if string.sub(code,a,a) == "1" then
	return a
  else
	return 0
  end
end
local b = 0
for i=1,#binary do
  local b = b + getDecimal(i,binary)
end
term.clear()
term.setCursorPos(1,1)
print("")
print(binary.." in decimal is "..B)/>

or you can do
> pastebin get RjedXHpP binary

Thanks in advance.
theoriginalbit #2
Posted 08 September 2013 - 09:03 PM
Ok so I'm not too sure why you're doing that loop, and why your'e doing it. One of your main problems is that you're also localising your variables in those loops, you don't want to localise a and b inside the loops otherwise you forget the numbers you just made. A suggestion I would make is to remove the loop in your getDecimal and to do the following

local function getDecimal(place,code)
  --# if the string number was 1
  if string.sub(code,place,place) == "1" then
	--# return 2 to the power of the length (since binary is base-2) minus the currently checking position (since binary is right->left not left->right)
	return 2^(#code - place)
  end
  --# else return 0
  return 0
end
Then just remove that local in your b loop and you should be good.

However that being said, this method that you're using is quite slow, and there is already a way to do this in Lua that is much quicker! Just use tonumber and tell it that the string is in base 2… Ultimate solution:


term.clear()
term.setCursorPos(1,2)
write("Binary number: ")
local binary = read()
local b = tonumber(binary, 2)
if not b then
  error("Input not binary", 0)
end
print( binary.." in decimal is "..b )