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

后端 未结 9 1722
南旧
南旧 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 08:07

    Here's some code, but I think the earlier answers will do it for you. This is just to show some sort of test code to copy and past into a simple console project (the WriteBits method by be of help):

    static void Main(string[] args)
        {
            int b1 = 255;
            WriteBits(b1);
    
            int b2 = b1 >> 4;
            WriteBits(b2);
    
            int b3 = b1 & ~0xF ;
            WriteBits(b3);
    
            // Store 5 in first nibble
            int b4 = 5 << 4;
            WriteBits(b4);
    
            // Store 8 in second nibble
            int b5 = 8;
            WriteBits(b5);
    
            // Store 5 and 8 in first and second nibbles
            int b6 = 0;
            b6 |= (5 << 4) + 8;
            WriteBits(b6);
    
            // Store 2 and 4 
            int b7 = 0;
            b7 = StoreFirstNibble(2, b7);
            b7 = StoreSecondNibble(4, b7);
            WriteBits(b7);
    
            // Read First Nibble
            int first = ReadFirstNibble(b7);
            WriteBits(first);
    
            // Read Second Nibble
            int second = ReadSecondNibble(b7);
            WriteBits(second);
        }
    
        static int ReadFirstNibble(int storage)
        {
            return storage >> 4;
        }
    
        static int ReadSecondNibble(int storage)
        {
            return storage &= 0xF;
        }
    
        static int StoreFirstNibble(int val, int storage)
        {
            return storage |= (val << 4);
        }
    
        static int StoreSecondNibble(int val, int storage)
        {
            return storage |= val;
        }
    
        static void WriteBits(int b)
        {
            Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(b),0));
        }
    }
    

提交回复
热议问题