简体   繁体   中英

C bitwise and logical expression calculations?

I've been messing around with logical and bitwise expressions in C and wanted to know if these are correct? I just picked some random number for x and y then walked though the bits on paper.

x=0xA5 and y=0x57
Expression  Value
  x & y     0x05
  x | y     0xF7
 ~x | ~y    0xF5
  x & !y    0x01
  x && y    0x01
  x || y    0x01
 ~x || ~y   0x01
  x && ~y   0x01
int main (void){
  int x = 0xA5;
  int y = 0x57;

  printf("%#x\n", x & y);
  printf("%#x\n", x | y);
  printf("%#x\n", ~x | ~y);
  printf("%#x\n", x & !y);
  printf("%#x\n", x && y);
  printf("%#x\n", x || y);
  printf("%#x\n", ~x || ~y);
  printf("%#x\n", x && ~y);
  return 0;
}

0x5
0xf7
0xfffffffa
0
0x1
0x1
0x1
0x1

Short answer, no, they're not all correct. Why?

x = 0000 0000 1010 0101
y = 0000 0000 0101 0111

#3:
~x      = 1111 1111 0101 1010 (0xFFFFFF5A)
~y      = 1111 1111 1010 1000 (0xFFFFFFA8)
~x | ~y = 1111 1111 1111 1010 (0xFFFFFFFA)

#4:
!y = 0
x       = 0000 0000 1010 0101
!y      = 0000 0000 0000 0000
x & !y  = 0000 0000 0000 0000

What you're missing is ! is a logic not. Applying ! to any non 0 value gives 0. ~ is a bitwise negation. ~ inverts the 1's and 0's.

您可以在这里找到: http : //ideone.com/Xe0ch (我懒惰地在纯C语言中执行此操作,但是这些操作在C ++中应该产生相同的结果)在线编译器是检查工作的最快方法:)

a good way to check well be writing a program that well print the values.

printf("%#x",expression);

the prinf function wikipedia

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM