1

I have this code:

$a = pack('N',0b00111010000011110101011100100010);

$start = strlen($a)*8 -1;
$str = '';
for($k = $start; $k>=0; $k--) {
    $bit = ($a >> $k) & 1;
    $str .= $bit;
}

var_dump($str);

output must be this:

00111010000011110101011100100010

but show me this output:

00000000000000000000000000000000

what is wrong in this code ??

0

3 Answers 3

1

There is a typo.

$a = pack('N',0b00111010000011110101011100100010);
               ^
Sign up to request clarification or add additional context in comments.

Comments

0

I changed code to this and my problem solved:

$a = pack('N',0b00111010000011110101011100100010);

$str = '';
for($j=0;$j<strlen($a); $j++) {
    $byte = substr($a, $j, 1);
    $num = ord($byte);
    for($k=7; $k>=0; $k--) {
        $bit = ($num >> $k) & 1;
        $str .= $bit;

    }

}
var_dump($str);

Comments

0

another way is to shift the bit you're reading instead of the data byte, same thing really. No need to substr() a single byte, array subscript notation works

$a = pack('N',0b00111010000011110101011100100010);
$str = '';
for ($i=0; $i<strlen($a); $i++) {
    $byte = ord($a[$i]);
    $mask = 0x80;
    while ($mask > 0) {
        $str .= ($byte & $mask) ? '1' : '0';
    }
}

echo "$str\n";

Edit: fixed typos, now runs

2 Comments

your code execution time is very long. in my browser its time was infinite and finaly finished with overflow memory size !! but execution time of my solution is about 1 second.
oops, had two bugs in there. try now. Don't know why it would not have exited, though, on my system it immediately errored out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.