Last active
December 25, 2016 21:20
-
-
Save fbender/6b8d927e14f298edb3da to your computer and use it in GitHub Desktop.
Base64 for MATLAB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function b64 = base64( str ) | |
%BASE64 Encode string (array of chars) into Base64 | |
% Currently seems to fail for any input > 4 characters. :( | |
%% Settings | |
% Valid output codes to choose from. | |
base64Chars = char([65:90, 97:122, 48:57, 43, 47]); % +/ per RFC 2045 et al. | |
%base64UrlChars = char([65:90, 97:122, 48:57, 45, 95]); % -_ per RFC 4648 §4 | |
base64PadChar = '='; | |
% Process |x| bits (or |x/8| chars) at once. | |
readBufferSize = 4*8; % Multiple of 8 | |
%% Code | |
charCodes = uint8(str); | |
charCount = size(charCodes, 2); | |
encLength = ceil(4*charCount / 3); | |
padLength = mod(3 - mod(charCount, 3), 3) * 2; % 0, 2, or 4 bits | |
%b64Length = encLength + padLength/2; | |
% Buffer size needs to be divisable by 6. | |
%bitBuffer = uint8.empty(0, ceil(readBufferSize/6)*6); | |
bitBuffer = zeros(1, ceil(readBufferSize/6)*6, 'uint8'); | |
readCount = uint8(floor(readBufferSize/8)); | |
b64 = [blanks(encLength), repmat(base64PadChar, 1, padLength/2)]; | |
readIndex = 0; | |
writeIndex = 0; | |
while readIndex < charCount | |
% Read buffer. | |
for i = 1:readCount | |
bufferIndex = (i-1)*8 + 1; | |
if readIndex+i > charCount | |
bitBuffer(bufferIndex:end) = NaN; %0; % :i*8?? | |
break; | |
end | |
bitBuffer(bufferIndex:i*8) = bitget(charCodes(readIndex+i), 8:-1:1); | |
end | |
% Process buffer. | |
for i = 1:6:size(bitBuffer, 2) | |
writeIndex = writeIndex + 1; | |
if writeIndex > encLength | |
break; | |
end | |
b64Code = bin2dec(num2str(bitBuffer(i:i+5))) + 1; | |
b64(writeIndex) = base64Chars(b64Code); | |
end | |
% Increment read index. | |
readIndex = readIndex + readCount; | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment