基本数据类型的位数 [英] Number of bits in basic data type
问题描述
这里有一些想法.我正在学习,所以可能会有错误,甚至缺少一些基础知识.
Here's a couple of thoughts.I'm learning so there might be mistake(s) and even missing some basics.
-
sizeof
运算符返回字节数.
-
number of bits in byte
不是恒定值(请纠正我,但它是char的位数).
- 我想知道变量占用了多少位,如果不对char中的位数进行假设,sizeof不会告诉我.
sizeof
operator returns number of bytes.number of bits in byte
is not constant value(correct me but it's number of bits char has).- I want to know how many bits variable occupies, and sizeof won't tell me that without making assumptions about number of bits in char.
所以我想出了这段(可能不必要的)代码:
So I came up with this piece of (probably unnecessary) code:
#include <stdio.h>
#include <math.h>
#include <limits.h>
int main(void)
{
double bits;
bits=sizeof(int)*log10(UCHAR_MAX+1)/log10(2);
printf("Bits = %lf\n", bits);
return 0;
}
是否有更简单(标准)的方法来检查给定类型占用了多少bits
?
CHAR_BIT * sizeof(type)
可以完成工作,但是是否有标准的one argument
宏/函数可以帮我做到这一点?
拥有较好数学背景的人可以检查我的代码是否始终会给出正确的答案.
Is there easier (standard) way to check how many bits
given type occupies?
CHAR_BIT * sizeof(type)
will do the job, but is there standard one argument
macro/function that does that for me?
Someone with better mathematical background could check if my code will be always giving correct answers.
推荐答案
如果要检查机器实际用于单个字符的位数,请使用CHAR_BIT
宏(请注意,sizeof (char)
将始终返回一个根据定义,尽管每个字符的实际分配大小可能会更高(甚至32位),尽管很浪费)
If you want to check for how many bits the machine actually used for a single char use the CHAR_BIT
macro (note that sizeof (char)
will always return one by definition though the actual allocation size per char may be still taller (even 32bits) though wasteful)
我不知道任何预定义的宏,但是
I am not aware of any predefined macro, but
#define REAL_BITS(type) (CHAR_BIT*sizeof(type))
足够
这篇关于基本数据类型的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!