Bitwise operation gives incorrect result

I'm fairly new to bitwise operations so I apologize ahead of time if my question seems poorly worded or not fit for stackoverflow. Recently, I've been toying with the bitwise AND operation by simply just printing out the results of expressions using the & symbol between binaries (in some expressions I use the bitwise AND between binaries and decimals). For example, I know that 110 & 4 equals 4 because 110 & 4 equates to 110 & 100 and

 1 1 0
 1 0 0
-------
 1 0 0

I get this result after printing it in C as well as inputting the values into a bitwise operation calculator. However, I get confused when certain equations like these arise,

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    printf("%Xn", 010 & 2); //prints out 0?!?!?
    printf("%Xn", 10 & 2); //prints out 2
    printf("%Xn", 011 & 010); //prints out 8?!?!?
    return 0;
}

I'm not sure why the first line of main prints out 0 because my understanding that 010 and 10 are the same binary (please correct me if I'm wrong) and 010 & 010 should equal 010 which equates to 2 . Lastly the last output completely throws me off guard because what I expected it to print out was,

 0 1 1
 0 1 0
-------
 0 1 0

However, the actual output is 8.

Lastly, I have one quick question about how these bitwise operations turn into booleans. For example, I've seen coders use these expressions as conditions in if statements such as

int byte;
scanf("%d",&byte);
if(byte & 2){
.....
}

Does byte & 2 equate to true as long as the result isn't 0? Any advice is appreciated.

EDIT : I see why my question was unclear now, for I forgot to mention the type of integer constant I was working with. My intention was to use binaries rather than octals so I apologize for this confusion.

EDIT2 : Now it seems that the above if statement isn't working when I input 0b010 into the console. However, 0b010 & 2 equates to 2 so what could be potentially causing this?

int byte;
scanf("%d",&byte);
if(byte & 2){
    //doesn't work when I input 0b010
}
if(0b010 & 2){
    //statement gets executed here but not the above, why?
}

In C:

  • 010 is octal for 8
  • 10 is decimal for 10.
  • 011 is octal for 9.
  • and, while we're at it ...

  • 100 is decimal for 100.
  • If you want binary you need to do something different:

  • Some compilers/standards accept 0b010 for binary constants.
  • Otherwise you need to convert to decimal, octal (starting 0 ), or hexadecimal (starting 0x )

  • The answer to the second part is that bitwise operators do not "turn into booleans". C interprets any zero or null value as false, in an if statement, for example, and any non-zero value as true. In non boolean contexts they're just numbers, pointers, whatever.

    链接地址: http://www.djcxy.com/p/75010.html

    上一篇: 按位包含OR运算符的目的是什么?

    下一篇: 按位操作会产生不正确的结果