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

each character from a string into a decimal into a binary.....

Started by Naxane, 27 July 2016 - 10:35 PM
Naxane #1
Posted 28 July 2016 - 12:35 AM


file is the input, B does nothing ignore B, file is put it then we iterate and get the decimal, and the problem is that i cant get the binary of the decimal
send help SOS
Emma #2
Posted 28 July 2016 - 01:20 AM
These are some steps to convert decimal number X to its binary equivalent:
For decimal number x:
  • Get the highest power of 2 that is less than the decimal number x:
  • 2n < x, (n=1,2,3,…)
  • The highest binary digit is equal to 1 (also any numbers skipped should be equal to 0):
  • dn = 1
  • Calculate the difference Δ of the number x and the power of 2, 2n:
  • Δ = x - 2n
  • Repeat from step #1 with the difference until the result is 0.
Example

Convert x=13 to binary.
Solution

n=3, 23=8 < 13
n=4, 24=16 > 13
So
n = 3
d3 = 1
Δ = 13 - 23 = 5
n = 2, x = Δ = 5
d2 = 1
Δ = 5 - 22 = 1
n = 1, x = Δ = 1
d2 = 0
n = 0, x = Δ = 1
d0 = 1
Δ = 1 - 1 = 0
(d3d2d1d0) = 1101
So 13 in decimal is equal to 1101 in binary:
x = 1310 = 11012

PS: The fastest way to get the largest power of 2 that goes into X is by doing this:

local highestNumIntoX = math.floor(math.log(x) / math.log(2))
Edited on 27 July 2016 - 11:28 PM
Anavrins #3
Posted 28 July 2016 - 02:11 AM
This is my function for converting decimal into binary.

function toBits(n)
  local o = {}
  repeat
    o[#o+1] = n%2
    n = bit32.rshift(n, 1)
  until n == 0
  return o
end
a = toBits(32) will return {0,0,0,0,0,1}, basically a[ j ] == 1 if the bit of value 2^j is 1.
You can also easily convert it into a readable binary string with table.concat(a):reverse()
I'm not sure why you want to convert a decimal number into binary, if you're doing encryption and need to do bit operation, the bit32 api is much more suited for that.
If you don't know how to use bit32, maybe this is a bit too advanced for you. Crypto is hard.
Edited on 28 July 2016 - 03:53 PM