一个字节中有多少位(任意系统)
How many bits in a byte (Arbitrary System)
在任意系统中,其中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
更好。
相关文章:
- C++,系统无法执行指定的程序
- 复制列表初始化的隐式转换的等级是多少
- 在UNIX系统中使用DIR查找文件的字节大小
- while循环中while循环的时间复杂度是多少
- 错误处理.将系统错误代码映射到泛型
- 当系统的卷被修改时,如何修改WASAPI环回捕获卷
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 如何检查一个c++字符串中有多少相同的字符/数字
- C++有多少类型的循环
- 在C++游戏中与库存系统作斗争
- 文件系统:复制功能的速度秘诀是什么
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 在gtest.中使用fff.h模拟系统API
- 如何制作无限制照明系统
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 在使用分段寻址模式的 16 位系统上,"size_t"、"uintptr_t"、"intptr_t"和"ptrdiff_t"类型的实际大小是多少?
- 有没有办法测量应用程序/程序占用多少系统资源(例如 RAM)
- 一个字节中有多少位(任意系统)
- 可以创建的最大线程数是多少?在多线程时需要考虑系统配置吗?