1

Output of the following code:

 test1: 0x00000002 0b00000010 (1 bytes)                               
 test2: 0x000000fd 0b11111101 (1 bytes)                                
~test1: 0xfffffffd 0b4294967285 (4 bytes)

I don't understand why doing ~(test1) is different from ~(0x02) since test1=0x02 and everything is unsigned. It appears that ~(test1) does the proper complement but then adds 3 bytes of ones to the left.

#include <stdio.h>

int binConv(int num)
{
    if (num == 0)
    {
        return 0;
    }
    else
    {
        return (num % 2) + 10 * binConv(num / 2);
    }
}

int main()
{
    unsigned char test1;
    unsigned char test2;

    test1=0x02;
    test2=~(0x02);

    printf(" test1: 0x%08x 0b%08u (%d bytes)\n",test1,binConv(test1),sizeof(test1));
    printf(" test2: 0x%08x 0b%08u (%d bytes)\n",test2,binConv(test2),sizeof(test2));
    printf("~test1: 0x%08x 0b%08u (%d bytes)",~test1,binConv(~test1),sizeof(~test1));
    return 0;
}

Code on onlinegdb.com

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Yelneerg
  • 161
  • 2
  • 11

1 Answers1

2

This has nothing (in particular) to do with one's complement.

Your problem is in the binConv function.

You are giving it a 32 bit value, and converting each bit to a base 10 digit. That's 1032. That value will not fit in an int.

You should also be passing unsigned values to and from binConv.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Doug Currie
  • 40,708
  • 1
  • 95
  • 119
  • While you are correct that there is an issue with passing that to binConv, that wasn't the real issue. The comments gave the answer I was looking for about integer promotion – Yelneerg Jan 05 '18 at 23:06