Juce style Base64 encoding in php


#1

hi,


I needed Base64 equivalency between juce and php, so I just coded the equivalent of toBase64Encoding(), maybe that can be useful to some of you.
I'm pretty sure it could be done in just a few lines, but I choosed to be as close as possible to the juce code, so it is quite a copy-paste :)
It seems to work pretty well as far as I tested.
I'm totally a newb in php thought, so if you find wome weirdnesses in there let me know!
 


function getBitRange ($data, $bitRangeStart, $numBits)
{
    $res = 0;
    $byte = $bitRangeStart >> 3;
    $offsetInByte = $bitRangeStart & 7;
    $bitsSoFar = 0;
    
    while ($numBits > 0 && $byte < count($data))
    {
        $bitsThisTime = min ($numBits, 8 - $offsetInByte);
        $mask = (0xff >> (8 - $bitsThisTime)) << $offsetInByte;
        $res |= ((($data[$byte] & $mask) >> $offsetInByte) << $bitsSoFar);
        
        $bitsSoFar += $bitsThisTime;
        $numBits -= $bitsThisTime;
        ++$byte;
        $offsetInByte = 0;
    }
    return $res;
}

function juceStyle64encode ($stringToEncode)
{
    $base64EncodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
    
    $size = strlen ($stringToEncode);
    $data = array();
    
    for ($i = 0; $i < $size; ++$i)
        $data[] = ord ($stringToEncode[$i]);
    
    $numChars = floor ((($size << 3) + 5) / 6);
    
    $encodedString = $size . '.';
    
    for ($i = 0; $i < $numChars; ++$i)
        $encodedString .= $base64EncodingTable[getBitRange ($data, $i * 6, 6)];
    
    return $encodedString;
}

 

so that :


String s ("whatever");
MemoryBlock mb (s.toRawUTF8(), s.getNumBytesAsUTF8());
String encodedString (mb.toBase64Encoding());

would be :

$encodedString = juceStyle64encode ("whatever");