'How does & work when the operands are of different size in C [closed]
I am just wondering could someone explain the following code and what is being output?
I am kind of confused about how it works? does it involve integer promotion or type conversion when & is being used here? Could someone explain a bit? I tried to do some bitwise & between two numbers, but results don't come out to be expected.
int main()
{
printf("Hello World\n");
int x1 = 11 & 0xa; // 0x132d
int x2 = 11 & 0xb; // 0x132d
int x3 = 11 & 0xc; // is this 0011 & 1100 ?
int x4 = 11 & 0xd; // is this 0011 & 1101?
int x5 = 11 & 0xe; // is this 0011 & 1110?
int x6 = 11 & 0xf; // is this 0011 & 1111?
printf("%0d \n", x1);
printf("%0d \n", x2);
printf("%0d \n", x3);
printf("%0d \n", x4);
printf("%0d \n", x5);
printf("%0d \n", x6);
return 0;
}
and this is the output:
Hello World
0
1
4
5
4
5
Solution 1:[1]
All about your target type either decimal or binary as 0xB & 0xC. (1011 & 1100 in binary).
According to your code --> output is:
Hello World
10
11
8
9
10
11
Solution 2:[2]
How does & work when the operands are of different size
When an operands is narrow, it is promoted to an
intorunsigned, whichever type encompassed the range of the narrow object. (Does not apply here are both operands are alreadyints.Then the lower ranked operand is converted to the higher one.
Then
&is applied - both operands now being the same time. The result is of this common type.
int x3 = 11 & 0xc; // is this 0011 & 1100 ?
No. It is like 0xB & 0xC. (1011 & 1100 in binary)
Solution 3:[3]
In computer memory,it just like that.
32-bit operating system
11 & 0xa; 00001011 & 1010
11 & 0xb; 00001011 & 1011
11 & 0xc; 00001011 & 1100
11 & 0xd; 00001011 & 1101
11 & 0xe; 00001011 & 1110
11 & 0xf; 00001011 & 1111
When you use operation symbol &
11 & 0xa;
`0`0000000000000000000000000001011 & 000000000000000000000000`0`0001010
-> `0`0000000000000000000000000001010
-> output 10
when you change 11 to -11
-11 & 0xa;
`1`0000000000000000000000000001011
-> `1`1111111111111111111111111110100
-> `1`1111111111111111111111111110101 & 000000000000000000000000`0`0001010
-> `0`000000000000000000000000000000000
-> output 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Software Tester at ExpandCart |
| Solution 2 | |
| Solution 3 |
