Skip to content

Commit

Permalink
Checks for single bits within an integer
Browse files Browse the repository at this point in the history
  • Loading branch information
bajb committed Dec 4, 2014
1 parent 2c84f20 commit 26af7b3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
19 changes: 19 additions & 0 deletions inc/GlobalFunctions.php
Original file line number Diff line number Diff line change
Expand Up @@ -716,3 +716,22 @@ function hydrate($destination, $source, array $properties, $copyNull = true)
}
}
}

if(!function_exists('is_single_bit'))
{
/**
* Check to see if an integer is a single bit, or a combination
*
* @param int $bit Bit to check
*
* @return bool
*/
function is_single_bit($bit)
{
if($bit === 1)
{
return true;
}
return $bit > 0 && bcmod($bit, 2) == 0 && ($bit & ($bit - 1)) == 0;
}
}
23 changes: 23 additions & 0 deletions tests/GlobalFunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ public function testGetNamespace()
public function testBuildPath()
{
$this->assertEquals("a" . DIRECTORY_SEPARATOR . "b", build_path("a", "b"));
$this->assertEquals("a" . DIRECTORY_SEPARATOR . "b", build_path("a", "b"));
}

public function testBuildWindowsPath()
Expand All @@ -224,6 +225,7 @@ public function testBuildUnixPath()
public function testBuildCustomPath()
{
$this->assertEquals("a|b", build_path_custom("|", ["a", "b"]));
$this->assertEquals("a|b", build_path_custom("|", [0 => "a", 1 => "b"]));
}

public function testConcat()
Expand Down Expand Up @@ -397,6 +399,27 @@ public function testHydrate()
$this->setExpectedException("Exception");
hydrate(['' => ''], $source, []);
}

public function testSingleBit()
{
$this->assertTrue(is_single_bit(1));
$this->assertTrue(is_single_bit(2));
$this->assertTrue(is_single_bit(4));

$fails = [3, 5, 6, 7, 9, 10, 11, 13, 14, 15];
foreach($fails as $checkBit)
{
$this->assertFalse(is_single_bit($checkBit));
}

$checkBit = 4;
for($i = 0; $i < 10000; $i++)
{
$checkBit = bcmul($checkBit, 2);
$this->assertTrue(is_single_bit($checkBit));
$this->assertFalse(is_single_bit(bcsub($checkBit, 3)));
}
}
}

class PropertyClass
Expand Down

0 comments on commit 26af7b3

Please sign in to comment.