A"动态位域"用C

编程入门 行业动态 更新时间:2024-10-27 01:22:08
本文介绍了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

本文发布于:2023-05-25 10:58:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   QUOT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!