Search code examples
c#encodingbit-manipulationbitwise-operators32-bit

How to encode 8 4bit values into an Int32 and then get those back?


How can I put 8 4bit (0..15 or 0..F if you like hex ;) ) values into an Int32 (int) in C# and get those back? I need these for a game that I am writing or more specifically, editor for it (which will feature vertex manipulation like in Notch's failed 0x10c) and since there's already some legacy code and few levels built, I really can't break the format so I can use Int64 and encode 8 8bit values using BitConverter class ;).

I'm not very good at bitwise ops and those who tried to explain these to me so far have failed so yeah. Need help.


Solution

  • The main idea is to use left << shift and | to encode and & and right >> shift to decode. Suppose the values are organized as array:

     byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    
     int result = data
       .Select((value, i) => value << (4 * i))
       .Aggregate((x, y) => x | y); // or just .Sum() - Jeppe Stig Nielsen's idea
    

    Edit: for loop implementation:

     int result = 0;
    
     for (int i = 0; i < data.Length; ++i)
       result |= data[i] << (4 * i);
    

    To retrieve the index-th value (index is in [0..7] range)

     byte item = (byte) ((result >> (index * 4)) & 0xF);