Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Decode Base64 String in VFP6 1

Status
Not open for further replies.

CBellucci

Programmer
Apr 20, 2007
38
US
I know I can encode and decode Base64 strings using STRCONV in VFP9. Unfortunately, I'm tied to VFP6 for this project.

I have an Encode function that works great. I've decoded the strings in VFP9 using STRCONV and get the image I'm expecting.

So far, though, I've not found a Decode function that I can get to work. The following code "dies" (q < 0) on a + character:

FUNCTION DECSTR64
PARAMETERS S
LOCAL i,j,j,k,q,ch,s2,buf,tmpc
tmpc = 0
j = 0
buf = 0
s2 = ''
k = LEN(s)
FOR i = 1 TO k
ch = ASC(SUBSTR(s,i,1))
q = IIF((ch >= 97 AND ch <=122),25+ch-96,IIF((ch >= 65 AND ch <=90),ch-65,;
IIF((ch >= 48 AND ch <=57),ch+4,IIF(ch = 47,63,-1))))
IF q < 0 THEN
RETURN IIF(ch = 61,s2,'')
ENDIF
buf = BITOR(BITLSHIFT(buf,6),q)
j = j + 6
IF j >= 8 THEN
j = j - 8
tmpc = CHR(BITAND(BITRSHIFT(buf,j),255))
buf = BITAND(buf,BITLSHIFT(1,j) -1)
s2 = s2 + tmpc
ENDIF
ENDFOR
RETURN s2
ENDFUNC

Again, this function takes a Base64 string and decodes it to binary. Can anyone help?
 
I am no expert on this, but a quick google got me this:


Which has both encode and decode functions.

Regards

Griff
Keep [Smile]ing

There are 10 kinds of people in the world, those who understand binary and those who don't.
 
Actually, the decode looks very like yours!

Regards

Griff
Keep [Smile]ing

There are 10 kinds of people in the world, those who understand binary and those who don't.
 
I don't know the base64 specs, but:
+ = CHR(43), so ch = 43

This falls through the nested IIFs, assigning -1 to q, which appears to be a terminator.

The function is expecting the terminator to be the '=' character (ASCII 61). Any other character just forces the function to return an empty string.

Ok, so I just checked the specs, and reviewing the fox.wikis.com link.

The implementation of the decode function does not mirror the implementation of the encode function.

The encode function has + and / as characters 62 and 63 of the 'alphabet'.
The decode function recognises '/' (ASCII 47) and assigns it 63, but does not recognise '+' (ASCII 43)

Try replacing the embedded IIFs thusly:
Code:
q = IIF((ch >= 97 AND ch <=122),25+ch-96,IIF((ch >= 65 AND ch <=90),ch-65,;
    IIF((ch >= 48 AND ch <=57),ch+4,IIF(ch = 47,63,IIF(ch=43,62,-1)))))

 
That did it! Thank you, thank you, thank you!!!

Now I can continue on with my project... You're a lifesaver!
 
Weird that the author would use the basechars string to encode, but not to decode (using AT())
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top