以下结构之间有什么区别? [英] What's the difference between the following structures?

查看:90
本文介绍了以下结构之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct pack
{
 unsigned int a:9;
} p;




And

struct pack
{
 unsigned int a;
} p;


请说明区别.
预先感谢.


Please explain the difference.
Thanks in advance.

推荐答案

在第一个示例中,使用了一个位说明符.
通常,如果您的结构具有一个以上带有位说明符的成员(例如,示例中的":9"),则有意义.

它使您可以将一些成员打包在一起,这些成员通常会使用随后指定的更多位.这样做的真正原因不是节省一些内存.相反,它用于匹配某些硬件,硬件API或与其他第三方代码的二进制兼容性所需的结构的精确二进制布局.

有关详细说明,请参见: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/bitfields_xml.html [
In first sample a bit specifier is used.
Normally, if makes sense if you have a structure with more than one member with the bit specifier, such as ":9" in your sample.

It allows you to pack together some members which normally would use more bits then specified. The real reason for doing that is not saving of some memory. Rather, it is used to match exact binary layout of the structure required by some hardware, hardware API or binary compatibility with other 3rd-party code.

For detailed explanation, see: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/bitfields_xml.html[^].

Pay special attention for Note on Compatibility — it is not a trivial issue.

—SA


找到了答案: [ ^ ]


在第一个示例中,您明确地说"a"的值应占用多少整数位-0到8位(含0和8),总计9.
在第二个中,您说的是"a"占据了整个无符号int(通常为32位).

因此,如果每个结构都有一个名为"b"的实例,并且您执行了以下操作:
In the first example, you are explicitly saying how many bits of the integer should the value of "a" take up - bits 0 to 8 inclusive, for a total of 9.
In the second, you are saying that "a" occupies an entire unsigned int (usually 32 bits).

So if you had an instance of each strucure called "b" and you did this:
b.a = 0xffff;
printf("0x%x", (unsigned int) b);

然后,第一种方法将打印"0x1ff",第二种将打印"0xffff";

您可以使用它来将值组合为单个整数或字节,以帮助进行进程或外部硬件之间的通信.

Then the first way would print "0x1ff" and the second "0xffff";

You can use this to combine values into a single integer, or byte which can help with communications, either between processes or external hardware.


这篇关于以下结构之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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