I´m trying to break a number into an array of numbers (in php) in the way that for example:
- 25 becomes (16, 8, 1)
- 8 becomes (8)
- 11 becomes (8, 2, 1)
I don´t know what the correct term is, but I think the idea is clear.
My solution with a loop is pretty straightforward:
$number = rand(0, 128); $number_array_loop = array(); $temp_number = $number; while ($temp_number > 0) { $found_number = pow(2, floor(log($temp_number, 2))); $temp_number -= $found_number; $number_array_loop[] = $found_number; }
I also have a recursive solution but I can´t get that to work without using a global variable (don´t want that), the following comes close but results in arrays in arrays:
function get_numbers($rest_number) { $found_number = pow(2, floor(log($rest_number, 2))); if ($found_number > 0) { $temp_array[] = get_numbers($rest_number - $found_number); $temp_array[] = $found_number; } return $temp_array; } $number_array_recursive = array(); $number_array_recursive = get_numbers($number);
However, using something like pow(floor(log())) seems a bit much for a simple problem like this.
It seems to me that the problem calls for a recursive solution with some very simple maths, but I just don´t see it.
You can check each bit of the input number with the following (untested) function.
It checks the bit at position $pos in the variable $var by using a bitwise AND function. I’ll show you with 4-bit numbers for brevity.
If I want to check position 0 (the rightmost bit) of the number 3, I’d call the function like this:
Internally, checkBit is going to shift the constant 1 to the left 0 times because I passed in a 0. It’s then going to bitwise AND (&) the result with the number I passed in, 3. Since 3 = 0011 and 1 = 0001 the result is true, since the 0th bit is set in both arguments to the bitwise AND operator.