1

我有一个字符数组(比如 char charr[5]),其中包含 0/1(布尔数的 char 数组)。现在,我想将字符数组转换为 64 位整数(如果数组是 {0, 0, 0, 1, 0},它将给出 2)。怎么做 ?有库函数吗?

4

3 回答 3

3

No, there's no standard function for that. But it's pretty trivial:

uint64_t pack(const uint8_t *bits, size_t n)
{
  uint64_t x = 0, value = 1 << (n - 1);

  while(n > 0)
  {
    x += value * *bits++;
    n--;
    value /= 2;
  }
  return x;
}
于 2013-02-05T13:36:03.247 回答
1

Unwind 的基本思路是对的,但是实现起来比较复杂。这也有效:

uint64_t pack(const uint8_t *bits, size_t n)
{
  uint64 x = 0;
  for(;n > 0; n--) // For all input bits.
  {
    x <<= 1; // make room for next bit.
    assert(*bits <= 1); // It better be a 0 or 1.
    x += *bits++; // Add new bit on the end.
  }
  return x;
}
于 2013-02-05T16:51:13.757 回答
0

尝试以 2 为底的strtoll

int val = strtoll(input, NULL, 2);
于 2013-02-05T13:37:42.600 回答