我有这些可能的位标志。

1, 2, 4, 8, 16, 64, 128, 256, 512, 2048, 4096, 16384, 32768, 65536

所以每个数字就像服务器端的一个真/假陈述。因此,如果前 3 项(且仅前 3 项)在服务器端标记为“true”,则 Web 服务将返回 7。或者,如果上述所有 14 项均为真,我仍然会从网络服务返回一个数字,即所有这些数字的总和。

处理我返回的号码以找出哪些项目被标记为“true”的最佳方法是什么?

有帮助吗?

解决方案

if (7 & 1) { // if bit 1 is set in returned number (7)

}

其他提示

使用一些掩码操作员。用C语言:

 X & 8

是真的,如果设置了“ 8” s位。

您可以枚举钻头面具,并计算设置多少个。

如果确实是整个单词包含位的情况,并且您只想简单地计算设置了多少位,那么您本质上希望“人口计数”。获得人口数量的绝对最快方法是执行机器指令集中通常可用的本机“ popcnt”。

如果您不关心空间,可以设置一个数组 countedbits [... 由您的价值用预先计算的位计数索引。然后,单个内存访问计算您的位计数。

经常使用只是简单的 “位twiddling代码” 计算位计数:

(内根的方法):

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1; // clear the least significant bit set
}

(平行位总和,32位)

v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count

如果您以前从未见过the脚的黑客攻击,那么您就可以享受。

PHP很有趣,可能会使用其中一些算术来做有趣的事情。

认为这个问题很老可能对其他人有帮助。我将数字放入二进制中,因为这样更容易理解。该代码尚未经过测试,但希望逻辑清晰。该代码是 PHP 特定的。

define('FLAG_A', 0b10000000000000);  
define('FLAG_B', 0b01000000000000);
define('FLAG_C', 0b00100000000000);
define('FLAG_D', 0b00010000000000);
define('FLAG_E', 0b00001000000000);
define('FLAG_F', 0b00000100000000);
define('FLAG_G', 0b00000010000000);
define('FLAG_H', 0b00000001000000);
define('FLAG_I', 0b00000000100000);
define('FLAG_J', 0b00000000010000);
define('FLAG_K', 0b00000000001000);
define('FLAG_L', 0b00000000000100);
define('FLAG_M', 0b00000000000010);
define('FLAG_N', 0b00000000000001);

function isFlagSet($Flag,$Setting,$All=false){
  $setFlags = $Flag & $Setting;
  if($setFlags and !$All) // at least one of the flags passed is set
     return true;
  else if($All and ($setFlags == $Flag)) // to check that all flags are set
     return true;
  else
     return false;
}

用法:

if(isFlagSet(FLAG_A,someSettingsVariable)) // eg: someSettingsVariable = 0b01100000000010

if(isFlagSet(FLAG_A | FLAG_F | FLAG_L,someSettingsVariable)) // to check if atleast one flag is set

if(isFlagSet(FLAG_A | FLAG_J | FLAG_M | FLAG_D,someSettingsVariable, TRUE)) // to check if all flags are set

一种方法是循环浏览您的号码,将其左移动(即除以2),并将第一位与1使用&操作数进行比较。

由于没有PHP代码的确定答案,因此我添加了此工作示例:

// returns array of numbers, so for 7 returns array(1,2,4), etc..

function get_bits($decimal) {
  $scan = 1;
  $result = array();
  while ($decimal >= $scan){
    if ($decimal & $scan) $result[] = $scan;
    $scan<<=1; 
  }
  return $result;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top