只获取/设置长整型中特定的位。

huangapple go评论72阅读模式
英文:

Get / Set only specific bits in a long

问题

我有一个包含多个字段的48位结构,我希望能够读取和操作这些字段。我认为我已经理解了获取部分,但在设置部分遇到了困难。以下是一些示例代码:

问题是,在设置器中,如何只设置特定的位而不影响其他位。我理解这可以通过位移和一些掩码操作来实现。

例如:

public long data = 0x00;

public byte val1
{
    get => (byte)(data >> 0 & 3); //位 0-1
}
public byte val2 //位 2-9
{
    get => (byte)(data >> 2 & 0x3FC); //我认为这个可以工作?
    set
    {
       // ?
    }
}

基本上,我正在尝试从这个长整型中读取/插入一个值(int16、int32、byte等)。我尝试使用 BitVector,但最大的部分是16位,而其中一些字段的大小超过了这个(24位)。

英文:

I have a 48 bit struct with several fields that I want to be able to read and manipulate. I think i got the getter part, but I am struggling with the setter. Here is some sample code:

Question is, for the setter, how can I just set specific bits without affecting the others. My understanding is that accomplished by bit shifting and some mask operations.

For example:

    public long data = 0x00;

    public byte val1
    {
        get => (byte)(data >>0 & 3); //Bit 0-1
    }
    public byte val2 //Bit 2-9
    {
        get => (byte)(data >> 2 & 0x3FC); //I think this works?
        set
        {
           // ?
        }
    }

Basically I am trying to read / insert a value (int16, int32, byte, etc) into that long. I tried using BitVector but the biggest section is 16 bits and a couple of the fields are bigger than that. (24 bits).

答案1

得分: 1

Sure, here's the translated code:

未经测试但:

```cpp
const long mask = 0x3FC;
long i64 = value;
data = (data & ~mask) | (i64 << 2);

<details>
<summary>英文:</summary>

untested but:

const long mask = 0x3FC;
long i64 = value;
data = (data & ~mask) | (i64 << 2);


</details>



huangapple
  • 本文由 发表于 2023年5月18日 03:05:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定