views:

23

answers:

1

I am programming a small micro controller in BASIC. Basically it received some BASE64 encoded data and I need to decode it at my end using BASIC. I was wondering if there is any way to do that?

A: 

I don't know basic but you can start with this link: http://en.wikipedia.org/wiki/Base64 with a clear explanation of how the encoding works.

You need to decode a base64 encoded message so you should setup an array like

dim('A','B','C','D','E',....,'8','9','+','/')

(or wathever the basic syntax is) with the 64 index and read 4 chars from input. Find the corresponding value into the lookup table and use it to decode the message.

I will use the term char to indicate the chars you find into the encoded message and the term index to address the value they represent for the decoding algorithm.

If your basic support bitmask you can do it very quickly. if not, you have to use some clever multiplication/division.

  • multiply the first index and multiply it for 4 (modulus 255), divide the second index for 16, add the two result to obtain the first byte

  • multiply the second index for 16 (modulus 255), divide the third index for 4, add the two result to obtain the second byte,

  • multiply the third index for 16 (modulus 255), add the fourth index to obtain the third byte

repeat until the end of the message.

You need to pay attention the the padding characters: If you encounter an = sign you know that you hit the end of the encoded bytes and you have to stop the decoding knowing that:

  • if the third encoded char is a = you have to decode only the first byte;
  • if the fourth char is a = you need to decode two byte;

There aren't other cases.

Just another hint: sometimes the encoded messages is wrapped, you need to ignore the \n chars (or wathever combination of \r\n you can encounter).

Eineki