C# Language: Changing the First Four Bits in a Byte

后端 未结 9 1308
名媛妹妹
名媛妹妹 2021-02-14 07:01

In order to utilize a byte to its fullest potential, I\'m attempting to store two unique values into a byte: one in the first four bits and another in the second four bits. How

9条回答
  •  误落风尘
    2021-02-14 07:46

    public int SplatBit(int Reg, int Val, int ValLen, int Pos)
    {
        int mask = ((1 << ValLen) - 1) << Pos;
        int newv = Val << Pos;
        int res = (Reg & ~mask) | newv;
        return res;            
    }
    

    Example:

    • Reg = 135
    • Val = 9 (ValLen = 4, because 9 = 1001)
    • Pos = 2

    • 135 = 10000111

    • 9 = 1001
    • 9 << Pos = 100100
    • Result = 10100111

提交回复
热议问题