一个字节中有多少位(任意系统)

时间:2014-12-14 05:12:28

标签: c++

在8bit!= 1byte的任意系统中如何使用编程找到位数=字节?

我所拥有的是继续左移1直到我得到一些错误的值。但是如何编码呢?​​

3 个答案:

答案 0 :(得分:7)

您可以使用<climits> header中定义的CHAR_BIT宏。它是一个编译时常量,所以你不必在运行时做任何事情来解决它。

答案 1 :(得分:0)

您可以使用模板元程序来编译确定原始整数类型的位数。

此方法依赖于使用无符号类型,因为它简化了操作。此代码查找无符号字符的位数。

在确定unsigned char的位数后,我们可以使用sizeof opeator来确定这个&#34;任意系统下任何类型的位数。&#34;

#include <iostream>

template <unsigned char V=~unsigned char(0), int C=0>
struct bit_counter {
    static const int count = 
        bit_counter<(V>>1),C+1>::count;
};
template <int C>
struct bit_counter<0, C> {
    static const int count = C;
};

// use sizeof operator, along with the result from bit_counter
// to get bit count of arbitrary types.
// sizeof(unsigned char) always gives 1 with standard C++, 
// but we check it here because this is some kind of 
// "Arbitrary" version of the language.
template <typename T>
struct bit_count_of {
    static const int value = 
        sizeof(T) * bit_counter<>::count / sizeof(unsigned char);
};

int main() {
    std::cout << "uchar  " << bit_counter<>::count << std::endl;
    std::cout << "long   " << bit_count_of<long>::value << std::endl;
    std::cout << "double " << bit_count_of<double>::value << std::endl;
    std::cout << "void*  " << bit_count_of<void*>::value << std::endl;
}

答案 2 :(得分:0)

好吧,如果你愿意,可以算一下:

int bits = 0;
char byte = 1;

while(byte!=0)
{
    bits++;
    byte = byte << 1;
}

每次迭代都会找到byte中的位。当用完比特时,字节变为0。

但使用CHAR_BITS会更好。

相关问题