#### Archived

This topic is now archived and is closed to further replies.

# Making Bineary Code

## Recommended Posts

Well Guys... I better hope ya good at PHP otherwise I registrated here for nothing lol :D

Well now ontopic again...

[b]Example:[/b]
I have the number 7 (or 10 or 12 or 123 etc etc)
\$number = 7;

Now I want that the 7 will get splitted in 3 other numbers and on bineary way...
So that would be
2^0 = 1
2^1 = 2
2^2 = 4

1+2+4 = 7

So the output should be 1, 2, 4

Now I got this script:
[code]<?php
\$decimaal = 7;

\$binair = decbin(\$decimaal);
\$stukjes = str_split(\$binair);

// str_split split vanaf links, maar we rekenen vanaf rechts
array_reverse(\$stukjes);

\$delen = array();
foreach (\$stukjes as \$key => \$stukje) {
if (\$stukje == 1) {
\$delen[] = pow(2, \$key);
}
}

print_r(\$delen);
/** OUTPUT:
*  Array
*  (
*     [0] => 1
*     [1] => 2
*     [2] => 4
*  )
**/
?>[/code]

What is the problem with this:
Well for example I do
\$decimaal = 10;

The output will be not:
[code]Array
(
[1] => 2
[3] => 8
)[/code]

but is
[code]Array
(
[0] => 1
[1] => 4
)[/code]

other arrays must be equal to 0 then becaus the binary code would be for 10 in this example 0101

Now how should I do this :)

PS: if ya got a other code or something that likes on this sh1t i mean then also feel free to post

##### Share on other sites
Here's one way to do what I think you're asking:

[code]<?php
\$bin = sprintf("%b",100);
for (\$i=0;\$i<strlen(\$bin);\$i++)
\$binary[\$i] = \$bin{\$i};
\$revbin = array_reverse(\$binary);
\$tmp = array();
for(\$i=0;\$i<count(\$revbin);\$i++) {
\$x = pow(2,\$i)*\$revbin[\$i];
if (\$x != 0) \$tmp[] = \$x; }
echo implode(',',\$tmp);
?>[/code]

Ken

##### Share on other sites
Here's another one:

[code]<?php
// works up to dec64K-1, change for bigger numbers

echo convit(64032);

function convit(\$count) {
\$bin = decbin(\$count);
\$bin = substr("0000000000000000",0,16 - strlen(\$bin)) . \$bin;
echo \$bin . ' =  ';
for (\$i=0,\$j=15; \$i<16; \$i++,\$j--)
if (substr(\$bin, \$j, 1) == '1')
echo pow(2, \$i). ', ';
}
?> [/code]

Ronald  8)

##### Share on other sites
You end of with a trialing comma with your loop. I would use a temporary array and implod it:
[code]<?php
\$tmp = array()
for (\$i=0,\$j=15; \$i<16; \$i++,\$j--)
if (substr(\$bin, \$j, 1) == '1')
\$tmp[] = echo pow(2, \$i);
echo implode(', ',\$tmp);
?>[/code]

##### Share on other sites
or[code]
<?php
function i2b (\$a){
\$i = -1;
while ((\$x = pow(2,++\$i)) <= \$a) if (\$a & \$x) \$out[\$i] = \$x;
return \$out;
}

\$out = i2b(55);
echo array_sum(\$out),' = ',implode(' + ',\$out);
?>
[/code]