Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through n bit chunks of a byte string

I have a code like this:

$alphabet = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alphabetSize = count($alphabet);
$alphabetBitSize = ceil(log($alphabetSize, 2));
$bitSize = $length * $alphabetBitSize;
$bytes = random_bytes(ceil($bitSize/8));

What I need is reading $bitSize bits in a loop to generate a latin1 string using the alphabet. Now I am totally lost about how to do this with the $bytes I have. Most of the answers are using string functions to do this, but I guess I need something binary. Another option is doing it with hex maybe. Any hints?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I generally will use PHP’s built-in function unpack() to convert the bytes into a hexadecimal string and then to a binary string. I hope this helps.

$alphabet = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alphabetSize = count($alphabet);
$alphabetBitSize = ceil(log($alphabetSize, 2));
$bitSize = $length * $alphabetBitSize;
$bytes = random_bytes(ceil($bitSize/8));

$binaryStr = '';
foreach (unpack('C*', $bytes) as $byte) {
    $binaryStr .= sprintf("%08b", $byte);
}

$resultString = '';
for ($i = 0; $i < strlen($binaryStr); $i += $alphabetBitSize) {
    $bitSegment = substr($binaryStr, $i, $alphabetBitSize);
    $index = bindec($bitSegment) % $alphabetSize;
    $resultString .= $alphabet[$index];
}

echo $resultString;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading