From m204wiki
Jump to navigation Jump to search

Convert from base 64 to byte string

Note: Many $functions have been deprecated in favor of Object Oriented methods. The OO equivalent for the $Base64_Decode function is the Base64ToString (String function).

This function converts from a base 64 encoded string to the decoded byte string. It is identical to $Lstr_Base64_Decode with the (hopefully obvious) exception that it is not longstring capable. As such, $Lstr_Base64_Decode is recommended over $Base64_Decode as it is a more flexible version of the latter.

The $Base64_Decode function accepts one argument and returns a string result whose base 64 encoding is that argument.

The first argument is a string which is a base 64 encoding.

The returned value is the base 64 decoding of the argument string. If the argument is not a valid base 64 encoding, the null string is returned.


%DECODED = $Base64_Decode(string)

%DECODED is set to the base 64 decoding of string.

Usage notes

Because the maximum length of the argument is 255 bytes, if you have a longer stream to decode, you can do it in pieces, where any piece is a multiple of 4 bytes long (3 bytes are evenly packed into 4 bytes of a base 64 encoding). For example, if you have a valid base 64 string which is the concatenation of items in a Sirius $list and you wish to print that string, possibly producing multiple lines of length 60, you can use the following approach:

%S = '' FOR %I FROM 1 TO $ListCnt(%L) %T = $ListInf(%L, %I) REPEAT WHILE $LEN(%S) + $LEN(%T) > 80 %X = 80 - $LEN(%S) %U = %S WITH $SUBSTR(%T, 1, %X) PRINT $Base64_Decode(%U) %T = $SUBSTR(%T, %X + 1) %S = '' END REPEAT %S = %S WITH %T END FOR PRINT $Base64_Decode(%S)

As of Sirius Mods Version 6.8, you can do base 64 decoding of strings longer than 255 bytes using $Lstr_Base64_Decode, but if, as in the example above, the intent is to break the result into smaller chunks, anyway, there probably wouldn't be a marked difference between using $Base64_Decode or its longstring equivalent.

You may wish to check for an invalid base 64 encoding by checking for the null string return value from $Base64_Decode. Of course, if it is possible that the argument is null, the null string is a valid returned value. If you need to check for errors, and the null string is a possible argument value, you can use an approach such as the following:

%STR = $Base64_Decode(%IN) IF %STR EQ '' Then IF %IN NE '' THEN error code ... END IF END IF

$Base64_Encode is the inverse of $Base64_Decode.


Given the argument of length 4:

%JUNK = $Base64_Decode('ABCD')

%JUNK would be set to the byte string (of length 3) represented in hexadecimal as X'001083'.

Products authorizing $Base64_Decode