Base64 Clone

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
Posts: 33
Joined: May 21, 2016 22:55

Base64 Clone

Post by NorbyDroid »

Here is my code for a Base64 Encoder/Decoder.

The only issue I kno of for this is it adds extra data (1 or 2 bits) at the end of the file it restore

There is also some changes that could be made to improve it. One such change is keeping the Encoder/Decoder self-contained and not reloading the data each time it is called.

I hope this is helpful and handy for someone.

Code: Select all

Type tBytes
  Byte1 as Integer
  Byte2 as Integer
  Byte3 as Integer
  Byte4 as Integer
End Type

Dim tBytes as tBytes

Dim Char1 as String
Dim Char2 as String

' ----------------------------------------
' - Verify Input/Output
' - 255 240 15 > 63 63 0 15 > 255 240 15
' ----------------------------------------

Char1=EncodeBytes(255,240,15):Print Char1

tBytes.Byte1=Asc(Left$(Char1,1))  : tBytes.Byte2=Asc(Mid$(Char1,2,1))
tBytes.Byte3=Asc(Mid$(Char1,3,1)) : tBytes.Byte4=Asc(Right$(Char1,1))



If tBytes.Byte1=255 and tBytes.Byte2=240 and tBytes.Byte3=15 Then
  Print "Test Successful."
  Print tBytes.Byte1;tBytes.Byte2;tBytes.Byte3
End If

' ----------------------------------------
' - Verify Input/Output
' ----------------------------------------

Function EncodeBytes(Byte1 as Integer,Byte2 as Integer,_
                     Byte3 as Integer) as String
Dim encByte1 as Integer
Dim encByte2 as Integer
Dim encByte3 as Integer
Dim encByte4 as Integer

Dim CodeKey as String

EncByte1=Byte1 SHR 2
EncByte2=((Byte1 AND 3) SHL 4) OR (Byte2 SHR 4)
EncByte3=((Byte2 AND 15) SHL 2) OR (Byte3 SHR 6)
EncByte4=Byte3 AND 63

End Function

Function DecodeBytes(Byte1 as Integer,Byte2 as Integer,_
                     Byte3 as Integer,Byte4 as Integer) as String
Dim DecByte1 as Integer
Dim DecByte2 as Integer
Dim DecByte3 as Integer

Dim BinSet(122) as Integer
BinSet(43)=0 : BinSet(45)=1
For t as Integer=48 to 57:BinSet(t)=t-46:Next
For t as Integer=65 to 90:BinSet(t)=t-53:Next
For t as Integer=97 to 122:BinSet(t)=t-59:Next

Byte1=BinSet(Byte1) : Byte2=BinSet(Byte2)
Byte3=BinSet(Byte3) : Byte4=BinSet(Byte4)

DecByte1=(Byte1 SHL 2) OR (Byte2 SHR 4)
DecByte2=((Byte2 AND 15) SHL 4) OR (Byte3 SHR 2)
DecByte3=((Byte3 AND 3) SHL 6) OR (Byte4 AND 63)

End Function
Post Reply