viewtopic.php?f=8&t=29751&p=287273&hilit=base64#p287273
Never the less this version only decodes, inspired by:
https://rosettacode.org/wiki/Base64_dec ... #FreeBASIC
(there is also a encoder on rosetta for freebasic)
This code adds some rudimentary command line handling
and can be used for, by example, an image example header .b64
------=_NextPart_000_0000_6D8C1DB5.8458DF88
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
Content-Location: file:
<encoded data in base64>
Compiled with FreeBASIC-1.08.0-gcc-9.3
Code: Select all
' from https://rosettacode.org/wiki/Base64_decode_data#FreeBASIC
' added some basic file io for images 2021 thrive4
' is best to use regex to validate base64 encoding how ever not implemented here
' see https://stackoverflow.com/questions/6309379/how-to-check-for-a-valid-base64-encoded-string
' @"^[a-zA-Z0-9\+/]*={0,3}$"
' usage commandline example base64_tut.exe <filename>.b64
' output <filename>.jpg
' setup image or file input
dim filename as string = command(1)
dim image as string
dim itemnr as integer = 1
dim listitem as string
if instr(command(1), ".") <> 0 then
image = left(command(1), instrrev(command(1), ".") - 1) + ".jpg"
end if
Dim Shared As String B64
B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
"abcdefghijklmnopqrstuvwxyz" & _
"0123456789+/"
Function MIMEDecode(s As String ) As Integer
If Len(s) Then
MIMEdecode = Instr(B64,s) - 1
Else
MIMEdecode = -1
End If
End Function
Function Decode64(s As String) As String
Dim As Integer w1, w2, w3, w4
Dim As String mD
For n As Integer = 1 To Len(s) Step 4
w1 = MIMEdecode(Mid(s,n+0,1))
w2 = MIMEdecode(Mid(s,n+1,1))
w3 = MIMEdecode(Mid(s,n+2,1))
w4 = MIMEdecode(Mid(s,n+3,1))
If w2 >-1 Then mD+= Chr(((w1* 4 + Int(w2/16)) And 255))
If w3 >-1 Then mD+= Chr(((w2*16 + Int(w3/ 4)) And 255))
If w4 >-1 Then mD+= Chr(((w3*64 + w4 ) And 255))
Next n
Return mD
End Function
Dim As String msg64 = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" & _
"IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
' decode a base64 encoded file
if filename <> "" then
msg64 = ""
Open filename For input As 1
Open image For output As 2
Do Until EOF(1)
Line Input #1, listitem
' ghetto validation base64
select case true
case instr(listitem, " ") > 0
'nop
case instr(listitem, "-") > 0
'nop
case instr(listitem, ":") > 0
'nop
case instr(listitem, "%") > 0
'nop
case len(listitem) = 0
'nop
case else
msg64 = msg64 + listitem
end select
itemnr += 1
Loop
Print #2, Decode64(msg64)
close
end
end if
Print msg64
Print: Print(Decode64(msg64))
sleep 3000
' output test string
'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
'To err is human, but to really foul things up you need a computer.
' -- Paul R. Ehrlich
end