Reputation: 278
How can you convert a integer into it's bits representation?
For example number 9 representation in bits is: 10011
For example to convert a bit sequence into it's int representation you can do this:
$bits_sq = array(1,0,0,1,1);
function convert_bits_to_int($bits_sq){
$sum = 0;
for($i=0; $i < count($bits_sq); $i++){
$sum = $sum + $bits_sq[$i] * pow(-2, $i);
}
print $sum; // equals to 9
}
But I want the other way around.
Edit: DO NOT MISTAKE BITS WITH BINARY, THIS IS NOT THE DUPLICATE NEITHER HAS THE ANSWER IN THE ABOVE THREAD
Upvotes: -3
Views: 5948
Reputation: 1177
Below is a function I wrote to convert a decimal to an array of bits, with the lowest bit having an index of 1.
/* Function to convert positive decimal to array of bits with the lowest bit having an index of 1. @param int $int - Positive decimal to covert (Not sure if negative numbers will give correct result) @param int $min_bits (Optional) - Minimum number of elements in array @return array - Array of bits with the lowest indexed as 1 Example: decbits(5, 8) returns array(1=>1, 2=>0, 3=>1, 4=>0, 5=>0, 6=>0, 7=>0, 8=>0) */ function decbits($int, $min_bits=1) { // Convert int into binary $int = intval($int); $min_bits = intval($min_bits); $bin = decbin($int); $binstr = strval($bin); // Reverse string and populate array $binstr = strrev($binstr); $bit_array = str_split($binstr); // Ensure array has minimum number of elements $bit_array = array_pad($bit_array, $min_bits, 0); // Reindex array, starting at 1 array_unshift($bit_array,'0'); unset($bit_array[0]); return $bit_array; }
Upvotes: 0
Reputation: 712
Just dropping this here.
echo str_pad(decbin(1), 4, '0', STR_PAD_LEFT); // 0001
echo str_pad(decbin(7), 4, '0', STR_PAD_LEFT); // 0111
echo str_pad(decbin(9), 4, '0', STR_PAD_LEFT); // 1001
Upvotes: 0
Reputation: 17623
My php is rusty however if you want to do the reverse of this example
$bits_sq = array(1,0,0,1,1);
function convert_bits_to_int($bits_sq){
$sum = 0;
for($i=0; $i < count($bits_sq); $i++){
$sum = $sum + $bits_sq[$i] * pow(-2, $i);
}
print $sum; // equals to 9
}
then I suppose you want something like:
$bits_sq = convert_int_to_bits ($iValue);
function convert_int_to_bits ($iValue) {
$bits = array(); // initialize the array
do {
$bits[] = ($iValue & 1);
$iValue >>= 1; // shift the bit off so that we go to the next one
} while ($iValue); // continue as long as there are still some bits.
// we have the bits in reverse order so lets reverse it.
return array_reverse($bits);
}
Upvotes: 3
Reputation: 3415
You need to use decbin() to convert an integer to binary.
http://php.net/manual/en/function.decbin.php
Upvotes: 5