Get total value of individual ones in a binary string

I’m creating a cryptographically secure random string generator based on openssl_random_pseudo_bytes.

When the binary string is created, how do I get the binary representation like this 0011011011100101 and add the ones up.

So 0011011011100101 would convert to 9.

simple way would be to perform str_replace and remove the 0’s then check the length of the string

<?php 
function generate_secure_token($length = 16) {
	/* important! this has to be a crytographically secure random generator */	
	return bin2hex(openssl_random_pseudo_bytes($length));            
}

Ooops…didn’t read the whole thing…

Alternatively:

$str = '0011011011100101';
$num = array_sum(str_split($str));
$str = '00101101010101100101101001110101010';
$cnt = strlen(preg_replace("/0/", "", $str));

Of course for performance:

$str = '00101101010101100101101001110101010';
$cnt = strlen(str_replace("0", "", $str));

Edit: just as @cpradio said :smile:

Or:

$count = 0;
$str = '00101101010101100101101001110101010';
$replaced = str_replace("1", "", $str, $count);
// $count now has your sum

Or:

$str = '00101101010101100101101001110101010';
$statement = '$count = ' . preg_replace("/(\d)/", "$1+", $str) . '0;';
eval($statement);
// $count now has your sum

Maybe I’m missing something but…

substr_count($binaryString, '1');

???

1 Like

Thanks all but…

When you get raw output how do you get the string as zeros and ones? Sorry, I probably didn’t question it very clearly. Unless I’m missing something when you call openssl_random_pseudo_bytes you don’t get it in juman readable zeros and ones. I guess that is the question. :smile:

Thanks.

Found the answer: http://php.net/manual/en/function.base-convert.php

Ah, that explains the confusion. Going by your first example it looked like your wanted to get the number of positive bits not the equivalent value.

Glad you solved it :thumbsup:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.