Search code examples
c#bit-manipulationbitwise-operatorsbit-shiftbitwise-and

Get, Set, Read, converts bitwise in Short type value in C#


I have a short value X:

short X=1;  //Result in binary: 0000000000000001 
  1. I need to split them into an array and set the bits (say bit 6 and 10) //Result in binary: 0000001000100001
  2. I need to convert it back to short X value.

How can I do it painlessly? Could you please help?


Solution

  • If what you are referring to is a very basic encryption, then perhaps using the XOR (^) operator would be better suited for your needs.

    short FlipBytes(short original, params int[] bytesToSet)
    {
        int key = 0;
        foreach (int b in bytesToSet)
        {
            if (b >= 0 && b < 16)
            {
                key |= 1 << b;
            }
        }
    
        return (short)(original ^ key);
    }
    

    This method will both set and reset the bytes that you desire. For example:

    short X = 1;
    short XEncrypt = FlipBytes(X, 6, 10);
    short XDecrypt = FlipBytes(XEncrypt, 6, 10);
    
    // X        = 1    , Binary = 0000000000000001
    // XEncrypt = 1089 , Binary = 0000010001000001
    // XDecrypt = 1    , Binary = 0000000000000001