整数到布尔数组

integer to bool array

本文关键字:数组 布尔 整数      更新时间:2023-10-16

我想将像 83 这样的整数编码为二进制代码,1100101最快的方法是什么? 现在我正在使用以下代码:

ToBinary(int size, int value) {  
    size--;  
    this->code = new bool[size];  
    int in = size;  
    while (in >= 0) {  
        if(pow(2, in) <= value) {  
        this->code[size-in] = pow(2, in);  
        value -= pow(2, in);  
        } else   
            this->code[size-in] = 0;  
        in--;  
    }  
}

你可以利用使用>>进行换档,让事情变得容易得多:

ToBinary(int size, int value) {
    int i = size;
    this->code = new bool[size];
    while(i--) {
        this->code[i] = (value >> i) & 1;
    }
}

(或者,要按相反的顺序排列,this->code[size - i]

如果你在编译时知道大小,std::bitset<size> bits(value);将在其构造函数中做你想要的。