I'm doing a pretty trivial computer science homework revolving around bitwise operators in C, but I've run into an issue that I have no clue why it's happening. Here is the code I'm running.
#include <stdio.h>
int main(int argc, char *argv[]){
int bitPattern1 = 0x10011001;
int bitPattern2 = 0x01100110;
int bitPattern3 = 0xFFFFFFFF;
int bitPattern4 = 0x00000000;
/* pair 1 */
printf("bitPattern1 & bitPattern2 = %x\n", bitPattern1 & bitPattern2);
printf("bitPattern1 && bitPattern2 = %x\n", bitPattern1 && bitPattern2);
/* pair 2 */
printf("bitPattern1 | bitPattern2 = %x\n", bitPattern1 | bitPattern2);
printf("bitPattern1 || bitPattern2 = %x\n", bitPattern1 || bitPattern2);
/* pair 3 */
printf("bitPattern1 & bitPattern3 = %x\n", bitPattern1 & bitPattern3);
printf("bitPattern1 && bitPattern3 = %x\n", bitPattern1 && bitPattern3);
/* pair 4 */
printf("bitPattern1 | bitPattern3 = %x\n", bitPattern1 | bitPattern3);
printf("bitPattern1 || bitPattern3 = %x\n", bitPattern1 || bitPattern3);
/* pair 5 */
printf("bitPattern2 & bitPattern4 = %x\n", bitPattern2 & bitPattern4);
printf("bitPattern2 && bitPattern4 = %x\n", bitPattern2 && bitPattern4);
/* pair 6 */
printf("bitPattern2 | bitPattern4 = %x\n", bitPattern2 | bitPattern4);
printf("bitPattern2 || bitPattern4 = %x\n", bitPattern2 || bitPattern4);
return 0;
}
The problem happens with the first part of pair 4 which returns with the following result:
bitPattern1 | bitPattern3 = ffffffff
bitPattern1 || bitPattern3 = 1
Why is the bitwise operator returning the "f"s I've looked up the documentation and I though that the OR operator returns a 1 or a zero it seems that that example should return "11111111". Is it something to do with the hexadecimal numbers? I haven't been able to find anything on google.
Firstly, the input of your OR is
FFFFFFFF
in hex notation, which means that in binary (bitwise) terms it is11111111111111111111111111111111
. I.e. it is a lot more1
s than you quoted (32 bits, to be exact).Secondly, the bitwise OR in question should indeed return
1111111...1
in binary notation. And that is exactly what it returns. But when you print the result in hex notation, you getFFFFFFFF
. You explicitly requested hex notation by usingx
format specifier inprintf
.Unfortunately,
printf
has no format specifier for producing binary notation. However, converting hex to binary is a trivial task, since it is a straightforward replacement of each hex digit with four binary digits.F
stands for1111
, so as you can see, in bitwise terms your OR did indeed produce11111111111111111111111111111111
, as it should.