I have a dictionary with a lot of symbols, each of which is encoded in a huffman binary string.
Example:
Symbol | Huffman Code |
---|---|
you | 010 |
shall | 0111 |
not | 00111 |
pass | 00001 |
... | ... |
Therefore I encode the sentence "you shall not pass" like this: "01001110011100001".
Now I would like to divide the binary string into chunks of six characters and interpret each sextuplet as a character according to the base64 encoding. If the length of the string is not divisible by 6, I simply append zero at the end until it does.
So "you shall not pass" would be represented like this: 010011 100111 000010
which in base64 should be just TnC
.
To do this I managed to write the following PhP code, but I suspect that it could be done in some more elegant way, using some more efficient built-in function. I was looking to something like base64_encode()
, but if I try to base64_encode("01001110011100001")
, the function treats each single character as 1 byte, and outputs "MDEwMDExMTAwMTExMDAwMDE=". Could you give me some suggestion please?
<?php function binaryToChars($binarystring){ static $chars = array( "000000"=>"A","010000"=>"Q","100000"=>"g","110000"=>"w", "000001"=>"B","010001"=>"R","100001"=>"h","110001"=>"x", "000010"=>"C","010010"=>"S","100010"=>"i","110010"=>"y", "000011"=>"D","010011"=>"T","100011"=>"j","110011"=>"z", "000100"=>"E","010100"=>"U","100100"=>"k","110100"=>"0", "000101"=>"F","010101"=>"V","100101"=>"l","110101"=>"1", "000110"=>"G","010110"=>"W","100110"=>"m","110110"=>"2", "000111"=>"H","010111"=>"X","100111"=>"n","110111"=>"3", "001000"=>"I","011000"=>"Y","101000"=>"o","111000"=>"4", "001001"=>"J","011001"=>"Z","101001"=>"p","111001"=>"5", "001010"=>"K","011010"=>"a","101010"=>"q","111010"=>"6", "001011"=>"L","011011"=>"b","101011"=>"r","111011"=>"7", "001100"=>"M","011100"=>"c","101100"=>"s","111100"=>"8", "001101"=>"N","011101"=>"d","101101"=>"t","111101"=>"9", "001110"=>"O","011110"=>"e","101110"=>"u","111110"=>"+", "001111"=>"P","011111"=>"f","101111"=>"v","111111"=>"/"); $result = ""; while (strlen($binarystring)%6!=0){$binarystring .= "0";} while (strlen($binarystring)>0){ $substr = substr($binarystring,0,6); if (array_key_exists($substr, $chars)){$result .= $chars[$substr]; $binarystring = substr($binarystring,6);} else{throw new Exception("The variable is not a binary string.");} } return $result; } ?>