有什么用内部位域声明不同数据类型的? [英] What is the use of declaring different datatypes inside bitfields?

查看:417
本文介绍了有什么用内部位域声明不同数据类型的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个典型的使用位域是定义一个节省空间的变量小于8位。我不明白的是,宣布这些位作为short,int和长,布尔等。例如值

A typical use of bitfield is to declare a space efficient variable smaller than 8 bits. What i don't understand is the value of declaring those bits as short, int , long , bool etc. For example

typedef struct{
    int first:3,
    short second:3,
    char third:3
    } somestruct;

在上述情况下,所有的3个变量,即第一,第二和第三个是3位长。什么是首先声明变量为int的价值,第二短,第三为char?

In above case, all 3 variables, i.e. first, second and third are 3 bit long. What is the value of declaring the variable first as int, second as short and third as char?

或者,为什么连一个数据类型要求?我应该能够申报如上

Or, why is even a data type required? I should be able to declare the above as

typedef struct{
    first:3,
    second:3,
    third:3
    } modifiedstruct;

该modifiedstruct不承担任何数据类型变量的第一,第二和第三。除$ P $的pting 3位的字符,数字或浮动的责任应的的责任东西的东西。

GCC和G ++在linux上允许上述行为。

Both gcc and g++ on linux allow the above behavior.

推荐答案

事实上,C标准只允许位域的类型为签署int或unsigned int(和_Bool在C99)的。如果你可以抛出一个短,长或CHAR在那里,这是一个编译器扩展。

Actually, the C standard only allows bitfields to be of type signed int or unsigned int (and _Bool in C99). If you can throw a short, long or char in there, that's a compiler extension.

至于为什么,主要原因是符号性。试想一下:

As to why, the main reason is signedness. Consider:

struct {
   int s: 3;
   unsigned u: 3;
} bf;

bf.s = 7;
bf.u = 7;

这两个位域的都是人。不过,C preserves星座,所以:

Both of these bitfields are all ones. However, C preserves sign, so:

(int)bf.s == -1    // Because signed conversions preserve the sign bit
bf.s >> 1 == -1    // So do right shifts on signed values

,而

(int)bf.u == 7     // Because the source is unsigned and so just a series of bits
bf.u >> 1 == 3     // Unsigned right shifts are just moving bits around as well

有关编译器,允许字符,它可能是同一种思维。字符的默认符号性是实现定义的,所以如果你想有一个位域的符号性,以配合您的编译器的字符的符号性,您可以将其定义为char。

For compilers that allow char, it's probably the same sort of thinking. The default signedness of char is implementation-defined so if you want a bitfield's signedness to match your compiler's char's signedness, you can define it as char.

这篇关于有什么用内部位域声明不同数据类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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