Log in

View Full Version : Testing for Bit Value of Binary Numbers



Strangeplant
08-28-2006, 02:26 PM
Hi - I'm stuck again,

How do I test the various bits [values (0 or 1)] of binary numbers? (I can't find the php method so far.....) For example, I need to know if bit n is true or false, set or not set. (I do know how to move bits and compare binaries, etc., but that does not help me with what I need to do.)

I've decoded Hex into Binary with the function:
function hex2bin($source)
{
$strlen = strlen($source);
for ($i=0;$i<strlen($source);$i=$i+2)
{
$bin .= chr(hexdec(substr ($source, $i,2)));
}
return $bin;
} (Various logic operations will be based on a look-up and test of the retrieved & converted Hex strings. I've used Hex because I can read/edit them with a MySQL database editor)

Twey
08-28-2006, 02:52 PM
Since the returned binary value is a string, you can use PHP to access each bit as an array index.
function getBitValue($strBits, $flagNum) {
return $flagNum < 0 ? ($strBits[(-1 * $flagNum) - 1] === '1') :
($strBits[strlen($strBits) - $flagNum - 1] === '1');
}

getBitValue('0010111100101', 0); // true
getBitValue('0010111100101', 1); // false
getBitValue('0010111100101', -1); // false
getBitValue('0010111100101', -3); // true
getBitValue('0010111100101', -201); // false

mburt
08-28-2006, 07:57 PM
Hmm... That's clever. :D

Strangeplant
08-28-2006, 08:01 PM
I like it, but I must have something wrong in the hex2bin function because 31 should return 110001 to your function, and getBitValue returns 'NaB'; indicating that the input string is not binary. uggh!

Twey
08-28-2006, 08:10 PM
I'm not sure why you're doing all that :-\ What's wrong with baseconvert($num, 16, 2); ?

blm126
08-28-2006, 11:20 PM
The function is actually base_convert

Twey
08-28-2006, 11:52 PM
Yes. It is.

Don't we love PHP and its naming inconsistencies. :)

blm126
08-29-2006, 01:31 AM
Of course. lol

Strangeplant
08-29-2006, 02:23 PM
Twey, I had to laugh at myself when I read your message about base_convert(). What an easy solution! Thanks, obviously I need to spend more time reading the php man pages.

BTW, you need to left-pad with 0's because the leading 0's are stripped from a binary output string - strange.....

Twey
08-29-2006, 02:38 PM
Which is why I altered my function to remove the "NaB" stuff and simply assume that everything before the beginning of the string is a 0 :)