I don't understand why the behavior of the 1's complement in C is different when acting on a number vs acting on a variable storing a number

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

c
bit-manipulation
asked on Stack Overflow Jan 5, 2018 by Yelneerg • edited Jan 5, 2018 by chux - Reinstate Monica

1 Answer

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.

answered on Stack Overflow Jan 5, 2018 by Doug Currie • edited Jan 5, 2018 by chux - Reinstate Monica

User contributions licensed under CC BY-SA 3.0