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

后端 未结 9 1337
名媛妹妹
名媛妹妹 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

    Use bitwise AND (&) to clear out the old bits, shift the new bits to the correct position and bitwise OR (|) them together:

    value = (value & 0xF) | (newFirstFour << 4);
    

    Here's what happens:

                           value        : abcdefgh
                           newFirstFour : 0000xyzw
    
                                   0xF  : 00001111
                           value & 0xF  : 0000efgh
                      newFirstFour << 4 : xyzw0000
    (value & 0xF) | (newFirstFour << 4) : xyzwefgh
    

提交回复
热议问题