Search code examples
c#bitwise-operatorsbitwise-xor

Calculating bitwise inversion of char


I am trying to reverse engineering a serial port device that uses hdlc for its packet format.Based on the documentation, the packet should contain a bitwise inversion of the command(first 4 bytes), which in this case is "HELO". Monitoring the serial port when using the original program shows what the bitwise inversion should be:

 HELO -> b7 ba b3 b0
 READ -> ad ba be bb

The problem is, I am not getting values even remotely close.

public object checksum
    {

        get
        {
            var cmdDec = (int)Char.GetNumericValue((char)this.cmd);
            return (cmdDec ^ 0xffffffff);
        }
    }

Solution

  • You have to work with bytes, not with chars:

    string source = "HELO";
    
    // Encoding.ASCII: I assume that the command line has ASCII encoded commands only  
    byte[] result = Encoding.ASCII
      .GetBytes(source)
      .Select(b => unchecked((byte)~b)) // unchecked: ~b returns int; can exceed byte.MaxValue
      .ToArray();
    

    Test (let's represent the result as hexadecimals)

    // b7 ba b3 b0
    Console.Write(string.Join(" ", result.Select(b => b.ToString("x2"))));