-2

I am trying to find a hex value that will produce a result of 419326735, given the code below.

I know that a hex value of "0x2cd79929" produces a result of 697947948, although I am still trying to determine how.

This (code below) is part of a function that validates a firmware image given a hex value in the header.

I am relatively new to C, but have experience with C# and other OO languages, although I have no experience with bitwise operations.

#include <stdio.h>

char *hex_string;
unsigned int initial_val;
unsigned int final_val;

int main()
{
    hex_string = "0x2cd79929";
    
    sscanf(hex_string,"%x",&initial_val);
    
    final_val = initial_val << 0x18 |
                initial_val >> 0x18 |
                initial_val >> 8 & 0xff00 |
                (initial_val & 0xff00) << 8;
                
    initial_val = final_val;
    
    printf("value is %d",final_val);
    return 0;
}
  • 1
    A C book, tutorial or language reference manual is the right place to look up fundamental aspects of the language such as what certain operators do. Have you actually consulted any such resource? If so, what specifically do you not understand? – kaylum Jul 25 '20 at 07:10
  • 1
    Please also take some time go learn more about binary arithmetic. And also split up long and complex expressions into smaller and simpler expressions. Use pen and paper to write down the binary values (in binary) and do the expressions on paper to see what happens. And you need to know the platform and the sizes of the types used (for example, `int` could be 32 or 16 bits depending on system). – Some programmer dude Jul 25 '20 at 07:23
  • 1
    try outputting final value as `%x` – M.M Jul 25 '20 at 07:46

2 Answers2

2

The code basically does a byte swap of a 32-bit value. So the function is actually it's own reverse (feeding the output back into it will give you the original input.) To produce an output of 419326735 (0x18FE6B0F) you need an input of 0x0F6BFE18 (258735640)

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
1

That is a perfect example why you should not use decimal output when try to see what on the binary level function does.

changing the three last lines:

    //initial_val = final_val;
    
    printf("original\t%x\nvalue is \t%x",initial_val, final_val);
    return 0;
}

gives the output:

original    2cd79929
value is    2999d72c
0___________
  • 60,014
  • 4
  • 34
  • 74