-6

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?

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
Adriansyah
  • 124
  • 11

2 Answers2

2

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.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
0

htons() reverses the byte order on x86 machines. So your result is correct, just bytes swapped. Have a look at endianness.

PhilMasteG
  • 3,095
  • 1
  • 20
  • 27