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

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

    When I have to do bit-twiddling like this, I make a readonly struct to do it for me. A four-bit integer is called nybble, of course:

    struct TwoNybbles
    {
        private readonly byte b;
        public byte High { get { return (byte)(b >> 4); } }
        public byte Low { get { return (byte)(b & 0x0F); } {
        public TwoNybbles(byte high, byte low)
        {
            this.b = (byte)((high << 4) | (low & 0x0F));
        }
    

    And then add implicit conversions between TwoNybbles and byte. Now you can just treat any byte as having a High and Low byte without putting all that ugly bit twiddling in your mainline code.

提交回复
热议问题