why passing the return value of an asNumber'ed string breaks io?

88 Views Asked by At

I just started the matasano security challenge, and thought about learning IO at the same time. So now, i'm stuck on challenge 1 where I need to convert a string to base64.

Anyway i've come to the point where i need to convert from binary to decimal, here is my aproach:

binToDec := method( bin, <-- program does not enter this method
  dec := 0
  rem := 0
  i := 0

  while ( bin != 0,
    rem = bin % 10
    bin = bin / 10
    dec = dec + rem * 2 pow( i )
    i = i + 1
  )
  return dec
)

toBase64Ascii := method( slice,
  tmp := ""
  for( a, 0, slice size,  <-- construct a string to use with asNumber
    tmp = tmp .. slice at( a )
  )
  dec := binToDec( tmp asNumber ) <-- the line that make the whole thing crash
)

for ( a, 0, bin size, 6,
  tmp := toBase64Ascii( bin slice( a, a + 6 )
  ***some more code***
)

there is no error message or anything, the program just hangs indefinitely.

From the documentation: asNumber Returns the receiver converted to a number. Initial whitespace is ignored.

So i must say i'm quite confused here, what is happening ?

I would have done some more research but io is imposible to google for...

1

There are 1 best solutions below

2
Bergi On BEST ANSWER

I'm not sure what the expected input and output of your binToDec method is, but

while ( bin != 0,
  rem = bin % 10
  bin = bin / 10
  dec = dec + rem * 2 pow( i )
  i = i + 1
)

is likely an infinite loop. bin is a floating point number which is repeatedly divided by 10, which does not mean that it ever reaches 0.

I need to convert a string to base64.

Notice that there are asBase64 and fromBase64 methods on sequences.