Search code examples
c++creverse-engineering

How do bitwise operations work on expressions within variable assignments in C/C++?


I'm learning reverse engineering, and I have the following snippet which I am trying to make sense of:

var = strcmp("C:\\Windows\\System32\\svchost.exe", pe.szExeFile);
if (var)
  var = -(var < 0) | 1;
if (var)
{
  // additional code here
}

I think I understand most of what is going on here, but I'm confused about the purpose of the var = -(var < 0) | 1; line. I'm only very vaguely familiar with C/C++, so I'm having a hard time wrapping my head around what this line does.

I understand that it's a bitwise OR, but I'm unsure how the -(var < 0) works. Is the expression inside the parentheses evaluated to a 1 or 0 and then the negative is applied and the OR? Is it evaluated as a boolean? If so, how does the | work on a boolean?

Or am I totally missing the point here?


Solution

  • strcmp() returns one of three possible results:

    • < 0
    • 0
    • > 0

    Assumed common two's complement, after the first if the variable var will be

    • -1 for the former "< 0"
    • 0 for the former "= 0"
    • +1 for the former "> 0"

    However, the second if will be taken only if var is non-zero.

    The "mysterious" first if has no effect, as far as the source is concerned that you show.