Skip to content

Instantly share code, notes, and snippets.

@suin
Created February 23, 2012 03:17
Show Gist options
  • Save suin/1889760 to your computer and use it in GitHub Desktop.
Save suin/1889760 to your computer and use it in GitHub Desktop.
decToBits()
php > var_dump(PHP_INT_MAX);
int(9223372036854775807)
php > var_dump(decbin(PHP_INT_MAX));
string(63) "111111111111111111111111111111111111111111111111111111111111111"
php > var_dump(-1 * PHP_INT_MAX);
int(-9223372036854775807)
php > var_dump(decbin(-1 * PHP_INT_MAX));
string(64) "1000000000000000000000000000000000000000000000000000000000000001"
php > var_dump(decbin(-1));
string(64) "1111111111111111111111111111111111111111111111111111111111111111"
php > var_dump(decbin(-2));
string(64) "1111111111111111111111111111111111111111111111111111111111111110"
php > var_dump(decbin(-4));
string(64) "1111111111111111111111111111111111111111111111111111111111111100"
php > var_dump(decbin(-8));
string(64) "1111111111111111111111111111111111111111111111111111111111111000"
php > var_dump(decbin(-16));
string(64) "1111111111111111111111111111111111111111111111111111111111110000"
>_< (suinair:~/Desktop)
* php test.php
string(64) "1111111111111111111111111111111111111111111111111111111111111111"
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes) in /Users/suin/Desktop/test.php on line 13
<?php
function decToBits($dec)
{
var_dump(decbin($dec));
$bits = array();
for ( $i = 0; $dec; $dec >>= 1, $i += 1 )
{
if ( $dec & 0x01 )
{
$bits[] = pow(2, $i);
}
}
return $bits;
}
var_dump(decToBits(-1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment