Search code examples
chexinverse

How to inverse an integer in C?


I am trying to inverse a hexadecimal value. The result is wrong, however.

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>

int main(void)
{
    uint32_t acc = 0xBBD1;

    printf("0x%X", htons(~acc));    // prints 0x2E44 
}

Let's do the inversion by hand:

0xBBD1 = 1011 1011 1101 0001
~1011 1011 1101 0001 =
 0100 0100 0010 1110
0100 0100 0010 1110 = 0x442E

This means, the code should actually print 0x442E instead of 0x2E44.

What's wrong with my code?


Solution

  • Technically, no. But why are you using htons? It changes the endianess of a 16 bit datum to big-endian (that is, network byte order). First is your variable not 16 bit but 32 bit, so uint16_t acc = 0xBBD1 would be more appropriate. Second, as your on a little-endian machine, the bytes are exchanged, hence the output.