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

后端 未结 9 1303
名媛妹妹
名媛妹妹 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: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);
    }
    

提交回复
热议问题