Convert bool array to int32 ,unsigned int and double?

后端 未结 3 1420
甜味超标
甜味超标 2021-01-17 00:14

I\'ve bool arrays of sizes : 32, 48, 64 (each boolean represents a bit). how can I convert them to a number with a good performance( int, unsigned int, double48, double64)?

3条回答
  •  无人共我
    2021-01-17 00:45

    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);
    }
    

提交回复
热议问题