作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
首先,对于我这个问题的标题写得不好,我深表歉意。所以请母语为英语的人适当更改标题。我的问题很简单,如下:
我正在使用整数来存储一项的多种类型。例如:
TYPE A = 1
TYPE B = 2
TYPE C = 4
TYPE D = 8
TYPE E = 16
etc...
现在 DB 中的项目的类型值为 14,这意味着它已分配给 TYPE B+C+D。如果它的类型值为 9,则表示它已分配给 TYPE A+D。
我需要一个函数,我将提供单一类型的整数,并且该函数将返回整数类型的数组。
我可以遍历所有整数并将它们与数字进行比较,但这就是我现在使用的方法,但我正在寻找更有效的方法(如果存在的话)?
预先感谢您的帮助。
最佳答案
这是一个没有任何循环的函数(主要是为了好玩 :) ):
function getTypes($int)
{
$types = array('Type A','Type B','Type C','Type D','Type E');//defining types
$t = array_reverse(str_split(decbin($int)));//converting $int to an array of bits
$types = array_slice($types,0,ceil(log($int,2)));//slicing the array to the same size as number of bits in the $int
$t = array_combine($types,$t);// Creating a new array where types are keys and bits are values
return array_keys($t,1);// returning an array of keys which have a value of 1
}
但这并不意味着它是有效的。如果您使用位掩码,您最好使用按位运算符(如按位和 (&))来检查值。例如,如果你想检查你的整数是否包含类型 D 和类型 E,你应该这样做
if ($integer & 8 & 16)
为了检查每个单独的类型,我将使用一个带移位运算符的循环
function getTypes($int)
{
$result = array();
$types = array('Type A','Type B','Type C','Type D','Type E');
foreach($types as $type)
{
if ($int & 1)//checking if last bit is 1 (exactly the same as if($int%2) )
$result[]=$type;
$int>>=1;//shifting integer's bits to the right (exactly the same as $int = $int / 2)
}
return $result;
}
关于php - 如何在 PHP 中获取十进制数 "hidden"的二进制数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8050937/
我是一名优秀的程序员,十分优秀!