本文介绍了A"动态位域"用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题中,假设所有的整数都是无符号为简单起见。

In this question, assume all integers are unsigned for simplicity.

假如我还想写两个功能,包并解压,这让你收拾宽度较小的整数成,也就是说,一个64位整数。然而,整数的位置和宽度在运行时给出,所以我不能用C位域。

Suppose I would like to write 2 functions, pack and unpack, which let you pack integers of smaller width into, say, a 64-bit integer. However, the location and width of the integers is given at runtime, so I can't use C bitfields.

最快的是用一个例子来解释。为简单起见,我将与8位整数说明:

Quickest is to explain with an example. For simplicity, I'll illustrate with 8-bit integers:

             * *
bit #    8 7 6 5 4 3 2 1
myint    0 1 1 0 0 0 1 1

假设我想解压在位置5,宽度为2。这些整数都标有星号的两位。该操作的结果,应0B01。同样的,如果我解压在位置2,宽6,我会得到0b100011。

Suppose I want to "unpack" at location 5, an integer of width 2. These are the two bits marked with an asterisk. The result of that operation should be 0b01. Similarly, If I unpack at location 2, of width 6, I would get 0b100011.

我可以用bitshift左其次是bitshift右随便写的解压功能。

I can write the unpack function easily with a bitshift-left followed by a bitshift right.

但我想不出写一个相当于包的功能,它会做相反的一条明路。

But I can't think of a clear way to write an equivalent "pack" function, which will do the opposite.

说给出的整数0b11,在位置5它包装成敏(上面)和宽度2将产生

Say given an integer 0b11, packing it into myint (from above) at location 5 and width 2 would yield

             * *
bit #    8 7 6 5 4 3 2 1
myint    0 1 1 1 0 0 1 1

我想出了最佳涉及到很多concatinating位串与OR的,<<和>>。之前,我实现和测试它,也许有人认为一个聪明的快速解决方案?

Best I came up with involves a lot of concatinating bit-strings with OR, << and >>. Before I implement and test it, maybe somebody sees a clever quick solution?

推荐答案

关闭我的头顶,未经考验的。

Off the top of my head, untested.

int pack(int oldPackedInteger, int bitOffset, int bitCount, int value) {
    int mask = (1 << bitCount) -1;
    mask <<= bitOffset;
    oldPackedInteger &= ~mask;
    oldPackedInteger |= value << bitOffset;
    return oldPackedInteger;
}

在您的例子:

int value = 0x63;
value = pack(value, 4, 2, 0x3);

要在写入一个值34(可带两位)的偏移时,0x63是当前值。

To write the value "3" at an offset of 4 (with two bits available) when 0x63 is the current value.

这篇关于A&QUOT;动态位域&QUOT;用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:07