位运算小结

本文提供了一系列使用PHP实现的位操作函数,包括获取无符号整数最大值、判断奇偶性、位交换等实用功能,并介绍了位计数的两种方法。
<?php 
/*
 * @author: wusuopubupt
 * @date : 2013-09-09
 * 
 * PHP functions of bite operations 
 */

//get unsigned int max value
function max_int() {
	return ~(1 << 31);
}


//return $num*2
function multi2(&$num) {
	return ($num << 1);
}

//judge odd or even,eg:even(10,100,110...),odd(01,11,101...),return boolean value
function is_even($num) {
	return !($num & 1);
}


//switch a and b without temp
function switch_without_temp(&$a,&$b) {
	$a ^= $b;  
	$b ^= $a;
	$a ^= $b;
	
	/* and here is a similar method:
	$a = $a + $b;
	$b = $a - $b;
	$a = $a - $b;
	*/
}


//judge if is same sign
function is_same_sign($a,$b) {
	return !($a ^ $b);	
}

//judeg if is Factorial of 2 ,eg:10,100,1000...
//notice that -----------> (n-1):01,011,0111...
function is_factorial_of2($num){
	return n > 0 ? (n & (n - 1)) == 0 : false;  
}

//calculate m % (2^n)
function calculate_mod($m,$n) {
	return $m & ($n-1);
}

function get_average($a,$b) {
	return ($a + $b) >> 1; //division by 2
}

//get bit
function get_bit($m,$n) {
	return ($m >> ($n - 1) & 1);
}
//set bit to zero 
function set_bit_zero($m,$n) {
	return $m & ~(1 <<($m - 1));
}

// $num = -10;
// get_abs($num);
// echo $num;

?>














Bit Count:

<?php 
$num = 6;
$count = 0;
while($num) {
	$num = $num & ($num - 1);
	$count++;
}
/* another method:
 while($num) {
 	if(($num & 1) != 0) {
 		$count ++;
 	}
 	$num = $num>>1;
 } 
 */
var_dump($num);
var_dump($count);
?>


参考:http://blog.youkuaiyun.com/sgbfblog/article/details/8039147#reply

http://blog.youkuaiyun.com/zmazon/article/details/8262185

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值