gpt4 book ai didi

c++ - 将 bool 数组转换为 int32、unsigned int 和 double?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:57:21 25 4
gpt4 key购买 nike

我有大小为 32、48、64 的 bool 数组(每个 bool 值代表一个位)。如何将它们转换为具有良好性能的数字(int、unsigned int、double48、double64)?例如:

bool ar[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1}
int num = bitArrayToInt32(ar,32);// num = 65

最佳答案

O(n):

int bitArrayToInt32(bool arr[], int count)
{
int ret = 0;
int tmp;
for (int i = 0; i < count; i++) {
tmp = arr[i];
ret |= tmp << (count - i - 1);
}
return ret;
}

int main()
{
bool ar[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1};
int num = bitArrayToInt32(ar,32);
printf("number = %d\n", num);
}

关于c++ - 将 bool 数组转换为 int32、unsigned int 和 double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32410186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com