c++ - 这 "if(k.c[3] & c)"部分代码在做什么?

标签 c++ bitwise-and

#include<stdio.h>
#include<iostream.h>
main()
{
  unsigned char c,i;
  union temp
  {
    float f;
    char c[4];
  } k;
  cin>>k.f;
  c=128;
  for(i=0;i<8;i++)
  {
    if(k.c[3] & c) cout<<'1';
    else cout<<'0';
    c=c>>1;
  }
  c=128;
  cout<<'\n';
  for(i=0;i<8;i++)
  {
    if(k.c[2] & c) cout<<'1';
    else cout<<'0';
    c=c>>1;
  }
  return 0;
}

最佳答案

if(k.c[2] & c)

这称为按位与。

按位与的说明

   //illustration : mathematics of bitwise AND
   a = 10110101 (binary representation)
   b = 10011010 (binary representation)

   c = a & b 
     = 10110101 & 10011010 
     = 10010000 (binary representation)
     = 128 + 16 (decimal)
     = 144 (decimal)

按位与使用这个真值表:

X | Y | R = X & Y
---------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

请参阅这些有关按位与的教程:

关于c++ - 这 "if(k.c[3] & c)"部分代码在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6008702/

相关文章:

c++ - 在这种情况下要考虑的有效 C++ 数据结构

c++ - 敌人不会跟随玩家。 SDL2/C++

c++ - 将 QLabel 与自定义 QGraphicsItem 对齐

go - 为什么要比较在 golang 中使用按位与?

android - Android 按位运算符

c++ - 按位和的功能

c++ - Allegro5 al_create_display() 在 Mac OS Catalina 上崩溃

c++ - 64 位模运算的奇怪性能行为

objective-c - 合并多个 Bool 返回值而不短路

javascript按位并产生奇怪的结果