1 using ~ in C / C ++

I am using Visual Studio 2013.
Recently I tried a statement ~for 1 add-on:

int a = 10;
cout << ~a << endl;

Conclusion -11

But for

unsigned int a = 10;
cout << ~a << endl;

conclusion 4294967296

I do not understand why the conclusion is -11in the case of the signed int. Please help me with this confusion.

+4
source share
4 answers

When you put number 10 in a 32-bit signed or unsigned integer, you get

0000 0000  0000 0000  0000 0000  0000 1010

When you deny it, you get

1111 1111  1111 1111  1111 1111  1111 0101

32 4294967285 , -11 ( ), 32- 8- .

"" . , , "" ( ).

+11

~ ones-supplement , , , ,

0000 0000 0000 1010 (bin) / 10 (dec)

1111 1111 1111 0101 (bin)

(, -, 32 - 16 0.)

cout? . , . , ( 10 0). , : , 1. , -1, 111..111, () 000..000, +1: 000..001. : -1.

10, 111..110101000...001010, 1. : -11.

cout (), : .

+2

4294967285 is recorded in the memory in both cases (4294967296 correctly typo, 33 bits?), The value of this number depends on which character you use:

  • if it is signed, this number is -11.
  • if it is unsigned, then it is 4294967285

different interpretations of the same number.

You can reinterpret it as unsigned by doing it, the same result:

int a = 10;
cout << (unsigned int) ~a << endl;
+1
source

try it

unsigned int getOnesComplement(unsigned int number){

unsigned onesComplement = 1;
if(number < 1)
    return onesComplement;
size_t size = (sizeof(unsigned int) * 8 - 1) ;
unsigned int oneShiftedToMSB = 1 << size;

unsigned int shiftedNumber = number;
for ( size_t bitsToBeShifted = 0; bitsToBeShifted < size; bitsToBeShifted++){
    shiftedNumber = number << bitsToBeShifted;
    if(shiftedNumber & oneShiftedToMSB){
        onesComplement = ~shiftedNumber;
        onesComplement = onesComplement >> bitsToBeShifted;
        break;
    }
}
return onesComplement;
}
+1
source

Source: https://habr.com/ru/post/1542815/


All Articles