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

How many bits in a byte (Arbitrary System)

本文关键字:多少 系统 任意 字节 一个      更新时间:2023-10-16

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

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

您可以使用 <climits> 标头中定义的CHAR_BIT宏。 它是一个编译时常量,因此您无需执行任何操作即可在运行时弄清楚它。

您可以使用模板元程序在编译时确定基元整数类型的位计数。

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

在确定无符号字符的位计数之后,我们可以使用 opeator 的大小来确定此"任意系统"下任何类型的位计数。

#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;
}
好吧

,如果你愿意,你可以数数:

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

每次迭代都会在byte中找到大约位。当位用完时,字节变为 0。

不过,使用CHAR_BITS更好。