bit handling function

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
hello,

can anyone help me out with a bit handler?

it seems as if php's decbin() removes leading zeroes when converting
from hex....so for example decbin(hexdec()); basically removes any

i'm trying to convert some 32bit hex words into bin, and the first 12
bits need to be broken down into 3-bit sets for decoding a key of
sorts.  for example:

(on paper)
0x2101769:
-------normal bin-------  ----3-bit sets----
0010 0001 0000 0001 011 101 101 001

(in php)
decbin(hexdec(2101769)) = 1000000001001000001001

are there any functions that could break apart the number once i get
the conversion done correctly?
thanks!

Re: bit handling function

.oO(inexion)

Correct, because in a number leading zeros don't have any meaning:
1 = 01 = 001 ...

Pad the string with zeros to the required length of at least 12 chars,
take the last 12 chars from it and split them into groups of three:

<?php
\$hexCode = '2101769';
\$binCode = substr(sprintf('%012b', hexdec(\$hexCode)), -12);
\$parts = str_split(\$binCode, 3);
var_dump(\$parts);
?>

HTH
Micha

Re: bit handling function

If you want leading zeros in a 32-bit binary representation, try
\$binary = sprintf('%032b', \$number);

Lowest 3 bits:
\$low3 = sprintf('%03b', \$number & 0x0003);

Next 3 bits:
\$next3 = sprintf('%03b', (\$number >> 3) & 0x0003);

Next 3 bits:
\$another3 = sprintf('\$03b', (\$number >> 6) & 0x0003);

...and so on.

-A

Re: bit handling function

Thanks for the replies guys -

i got it working with this code:

\$tnum = array();
\$tnum[] = hexdec(\$targets['flags'][\$i]);
\$binCode = substr(sprintf('%012b', \$tnum[\$i]), -12);
\$parts = str_split(\$binCode, 3);
echo "flags: ".\$parts[0]." ".\$parts[1]." ".\$parts[2]." ".
\$parts[3]."<br />";

thanks!!

Re: bit handling function

.oO(inexion)

I would write the last line as

echo "flags: <br />";

But that's just personal preference.

You're welcome.

Micha

Re: bit handling function

Thanks for the replies guys -

i got it working with this code:

\$tnum = array();
\$tnum[] = hexdec(\$targets['flags'][\$i]);
\$binCode = substr(sprintf('%012b', \$tnum[\$i]), -12);
\$parts = str_split(\$binCode, 3);
echo "flags: ".\$parts[0]." ".\$parts[1]." ".\$parts[2]." ".
\$parts[3]."<br />";

thanks!!

Re: bit handling function

Thanks for the replies guys -

i got it working with this code:

\$tnum = array();
\$tnum[] = hexdec(\$targets['flags'][\$i]);
\$binCode = substr(sprintf('%012b', \$tnum[\$i]), -12);
\$parts = str_split(\$binCode, 3);
echo "flags: ".\$parts[0]." ".\$parts[1]." ".\$parts[2]." ".
\$parts[3]."<br />";

thanks!!