是位字段的任何更有效(计算),比屏蔽位和手工提取数据? [英] Is a bit field any more efficient (computationally) than masking bits and extracting the data by hand?

查看:128
本文介绍了是位字段的任何更有效(计算),比屏蔽位和手工提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有无数的小块数据,我希望能够推到一个较大的数据类型。比方说,假设,这是一个日期和时间。最明显的方法是通过这样的位字段。

I have a numerous small pieces of data that I want to be able to shove into one larger data type. Let's say that, hypothetically, this is a date and time. The obvious method is via a bit field like this.

struct dt
{
    unsigned long minute :6;
    unsigned long hour :5;
    unsigned long day :5;
    unsigned long month :4;
    unsigned long year :12;
}stamp;

现在,让我们pretend这个东西是有序的,这样声明的东西第一是比宣布事情以后再说,所以如果我通过可变它会是什么样子的第一个字母重新present位的较重要的位

Now let's pretend that this thing is ordered so that things declared first are at bits of higher significance than things declared later so if I represent the bits by the first letter of the variable it would look like:

mmmmmm|hhhhh|ddddd|mmmm|yyyyyyyyyyyy

最后,让我们pretend,我只是宣布一个unsigned long,并使用口罩拆分它,并转移到做同样的事情。

Finally, let's pretend that I simply declare an unsigned long and split it up using masks and shifts to do the same things.

unsigned long dateTime;

下面是我的问题:结果
有以下几种访问到分钟,小时等方法相当于什么样的电脑需要做的条款?或者是有编译器/电脑采用了与位域一些调皮的方法。

Here is my question:
Are the following to methods of accessing minutes, hours, etc. equivalent in terms of what the computer needs to do? Or is there some tricksy method that the compiler/computer uses with the bit fields.

unsigned minutes = stamp.minutes;
//versus
unsigned minutes = ((dateTime & 0xf8000000)>>26;

unsigned hours = stamp.hours;
//versus
unsigned hours = ((dateTime & 0x07C00000)>>21;

等。

推荐答案

编译器生成,你将明确写入访问位相同的指令。所以不要指望它与位域会更快。

The compiler generates the same instructions that you would explicitly write to access the bits. So don't expect it to be faster with bitfields.

在实际上,与位域严格地说,你别管他们是如何定位数据的话(除非你的编译器给你一些额外的保障。我的意思是C99标准没有定义的话)。手工操作的掩模,可以在至少第一和最后放置的两个最经常访问的字段中的系列,因为在这两个位置,它需要一个操作,而不是两个到外地隔离

In fact, strictly speaking with bitfields you don't control how they are positioned in the word of data (unless your compiler gives you some additional guarantees. I mean that the C99 standard doesn't define any). Doing masks by hand, you can at least place the two most often accessed fields first and last in the series, because in these two positions, it takes one operation instead of two to isolate the field.

这篇关于是位字段的任何更有效(计算),比屏蔽位和手工提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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