给定1和0的数组,将等效的二进制值转换为整数。例:[0,0,0,1]被视为0001,这是1的二进制表示。
[0, 0, 0, 1] ==> 1
[0, 0, 1, 0] ==> 2
[0, 1, 0, 1] ==> 5
[1, 0, 0, 1] ==> 9
[0, 0, 1, 0] ==> 2
[0, 1, 1, 0] ==> 6
[1, 1, 1, 1] ==> 15
[1, 0, 1, 1] ==> 11
#include <stddef.h>
unsigned binary_array_to_numbers(const unsigned *bits, size_t count)
{
unsigned total = 0;
int multiplier = 1;
for (int i = count - 1; i >= 0; i--)
{
if (bits[i] == 1)
{
total += (multiplier * bits[i]);
}
multiplier *= 2;
}
return total;
}