int main() {
unsigned int a=10;
a=~a;
printf("%u",a);
return 0;
}
Why the answer of the program is 4294967285 and not 65525.
binary value for 10 is = 0000 0000 0000 1010. If I invert the value I get 1111 1111 1111 0101. If I convert this value to decimals, I get 65525.
Cr BhargaviPosted Aug 16, 2023, 11:11 AM
Bitwise operations work in C++ is the reson for the results like that. You are performing the bitwise NOT (
~) operation ona, you are flipping all the bits in the binary representation of the number. To get 65525 from the inverted binary representation, you would need to interpret those bits as an unsigned 16-bit integer. However, in the context of your code, the data type used is a 32-bit unsigned integer, and that's why you're getting the result 4294967285.Jayaprakash LakshmanasamyPosted Aug 16, 2023, 2:40 PM
Thanks for the clarification. I changed the data type to unsigned short int and I got 65525.
Tahir AnsariPosted Aug 16, 2023, 10:22 AM
1. You have the initial value `a = 10`, which is represented in binary as `0000 0000 0000 1010`.
2. When you apply the bitwise NOT (`~`) operation to this value, each bit is inverted (0s become 1s and 1s become 0s). So, `~a` results in `1111 1111 1111 0101`.
3. Now, if you interpret the inverted binary value `1111 1111 1111 0101` as an unsigned integer, it will be converted to a decimal value.
The decimal conversion of `1111 1111 1111 0101` is 4294967285, not 65525.
To clarify:
- Decimal value 65525 is equivalent to binary `0000 0000 0000 0001 0000 1010 1101 0101`.
- Decimal value 4294967285 is equivalent to binary `1111 1111 1111 1111 1111 1111 1111 0101`.
So, the program is working correctly, and the answer is indeed 4294967285.
Saravanan GanesanPosted Aug 16, 2023, 10:11 AM
The result of the program is 4294967285 because of the way integer representation and bitwise operations work in C++. The variable
ais of typeunsigned int, which is typically a 32-bit data type.When you perform the bitwise NOT (
~) operation ona, you are flipping all the bits in the binary representation of the number. In your example, starting with the binary representation of0000 0000 0000 1010(which is 10), you flip the bits to get1111 1111 1111 0101. This is indeed the binary representation of 4294967285 in a 32-bit unsigned integer, not 65525.To get 65525 from the inverted binary representation, you would need to interpret those bits as an unsigned 16-bit integer. However, in the context of your code, the data type used is a 32-bit unsigned integer, and that's why you're getting the result 4294967285.