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

后端 未结 9 1689
南旧
南旧 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:56

    You first mask out you the high four bytes using value & 0xF. Then you shift the new bits to the high four bits using newFirstFour << 4 and finally you combine them together using binary or.

    public void changeHighFourBits(byte newHighFour)
    {
        value=(byte)( (value & 0x0F) | (newFirstFour << 4));
    }
    
    public void changeLowFourBits(byte newLowFour)
    {
        value=(byte)( (value & 0xF0) | newLowFour);
    }
    

提交回复
热议问题