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

后端 未结 9 1695
南旧
南旧 2021-02-14 07:23

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:48

    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

提交回复
热议问题