有没有的sizeof(c)中的位相同呢? [英] Is there a bit-equivalent of sizeof() in C?

查看:131
本文介绍了有没有的sizeof(c)中的位相同呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当应用于位字段的sizeof()不工作:

 #猫P.C
  #包括LT&;&stdio.h中GT;
  INT主(INT ARGC,字符** argv的)
  {
    结构{unsigned int类型位域:3; }等;
    fprintf中(标准输出,大小=%d个\\ N的sizeof(s.bitfield));
  }
#GCC c页-o p
  c页:在函数'主':
  c页:5:错误:sizeof的应用于位字段

......很明显,因为它不能返回浮点部分大小什么的。但是,它提出了一个有趣的问题。 有一个相当于在C,会告诉你的位数在变量/类型?理想情况下,它也将定期工种,以及像的字符 INT 的,除了位域。


  

更新:


  
  

如果没有语言的sizeof相当于()对于位域,什么是它计算的最有效的方式 - 在运行时!想象一下,你有依赖于这种循环,而你不希望他们如果更改位域的规模突破 - 而没有公平作弊,使位域的大小和环路长度的宏。 ; - )



解决方案

您不能确定C.您可以位字段的大小,但是,通过使用<$值找出其他类型的位大小C $ C> CHAR_BIT ,limits.h中找到。中位总人数就是 CHAR_BIT *的sizeof(类型)。

不要以为一个C字节是一个八位字节,它的至少的8位。有16个或甚至32比特字节实际机器。

关于您的编辑:
我想说一个位域 int类型的:N; 的大小的 N 的定义位。放在一个结构时,微胖位属于结构,而不是位字段。

我的建议是:不要使用位字段,但使用(阵列) unsigned char型和位掩码工作。这样,大量的行为(溢出,没有填充)被很好地定义。

Sizeof() doesn't work when applied to bitfields:

# cat p.c
  #include<stdio.h>
  int main( int argc, char **argv )
  {
    struct { unsigned int bitfield : 3; } s;
    fprintf( stdout, "size=%d\n", sizeof(s.bitfield) );
  }
# gcc p.c -o p
  p.c: In function ‘main’:
  p.c:5: error: ‘sizeof’ applied to a bit-field

...obviously, since it can't return a floating point partial size or something. However, it brought up an interesting question. Is there an equivalent, in C, that will tell you the number of bits in a variable/type? Ideally, it would also work for regular types as well, like char and int, in addition to bitfields.

Update:

If there's no language equivalent of sizeof() for bitfields, what is the most efficient way of calculating it - at runtime! Imagine you have loops that depend on this, and you don't want them to break if you change the size of the bitfield - and no fair cheating and making the bitfield size and the loop length a macro. ;-)

解决方案

You cannot determine the size of bit-fields in C. You can, however, find out the size in bits of other types by using the value of CHAR_BIT, found in limits.h. The size in bits is simply CHAR_BIT * sizeof (type).

Do not assume that a C byte is an octet, it is at least 8 bit. There are actual machines with 16 or even 32 bit bytes.

Concerning your edit: I would say a bit-field int a: n; has a size of n bits by definition. The extra padding bits when put in a struct belong to the struct and not to the bit-field.

My advice: Don't use bit-fields but use (arrays of) unsigned char and work with bitmasks. That way a lot of behaviour (overflow, no padding) is well defined.

这篇关于有没有的sizeof(c)中的位相同呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆