有什么用&放大器; C语言(AND)运算符? [英] what is use of &(AND) operator in C language?

查看:179
本文介绍了有什么用&放大器; C语言(AND)运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的#include<&stdio.h中GT;
#包括LT&;&math.h中GT;诠释的main()
{     INT N,I,J,长长的P,总和= 0,计数;
     scanf函数(%d个,&安培; N);
     长长的一个[N];
     对于(i = 0; I< N;我++)
          scanf函数(%LLD,&安培; A []);     为(J = 0; J< 64; J ++)
     {
         计数= 0;
         p值= POW(2,j)的;         对于(i = 0; I< N;我++)
             {
                 **如果(一个[1] - 安培; P)**
                 算上++;
             }         总和+ =(数*(计数1)* P / 2);
     }     的printf(%LLD,总和);
     返回0;
}

这是什么,如果在第二个语句for循环在这里做?
而为什么和放大器;在程序中使用?


解决方案

  

按位与运算符是一个符号:安培;.一个方便记忆是
  与布尔AND,和放大器的小版;&安培;,适用于更小的碎片
  (比特而不是字节,字符,整数,等等)。在本质上,一个二进制
  与简单地取入的每个位置的逻辑的位与
  二进制形式的数字。


例如,对于一个字节(char类型)工作:

EX。

  01001000&安培;
10111000 =
--------
00001000

的第一个数字的最显著位是0,因此我们知道结果的最显著位必须为0;在第二个最显著位的第二数目的位是零,因此,我们有相同的结果。唯一的时间,其中两个位都是1,这是唯一的时间的结果将是1,是从左侧的第五位。因此,

  72安培; 184 = 8

更多的例子

  unsigned int类型一= 60; / * 60 = 0011 * 1100 /
   unsigned int类型B = 13; / * 13 = 0000 * 1101 /
   INT C = 0;   C = A和b: / * 12 = 0000 * 1100 /

#include <stdio.h>
#include <math.h>

int main()
{

     int n,i,j;long long p,sum=0,count;
     scanf("%d",&n);
     long long a[n];


     for(i=0;i<n;i++)
          scanf("%lld",&a[i]);

     for(j=0;j<64;j++)
     {
         count=0;
         p=pow(2,j);

         for(i=0;i<n;i++)
             {
                 **if(a[i]&p)**
                 count++;
             }

         sum+=(count*(count-1)*p/2);
     }

     printf("%lld",sum);
     return 0;
}

what does if statement in second for loop do here? And why & is used in program?

解决方案

The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.

For instance, working with a byte (the char type):

EX.

01001000 & 
10111000 = 
--------
00001000

The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left. Consequently,

72 & 184 = 8

More example

   unsigned int a = 60; /* 60 = 0011 1100 */  
   unsigned int b = 13; /* 13 = 0000 1101 */
   int c = 0;           

   c = a & b;       /* 12 = 0000 1100 */ 

这篇关于有什么用&放大器; C语言(AND)运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆