第6天----【位运算进阶之-----位与(&)】七夕特别版

今天我们来学习C语言的位与。

文章目录

  • 一、基本应用:
  • 二、拓展应用:
    • 1. 提取特定位的值:
      • 小试牛刀:knife::
      • 拓展思考:
    • 2. 位掩码(Bitmasking):
    • 3. 清零特定位:
    • 4. 判断奇偶性:
  • 三、思考题:
  • 彩蛋:

第6天----【位运算进阶之-----位与(&)】七夕特别版_第1张图片


❤️C语言的位与(&)操作是一种按位运算符,用于对两个操作数的每个对应位执行逻辑与操作。它的操作规则如下:

  • 如果两个操作数对应位都为1,则结果的对应位也为1。(全1才1)
  • 如果两个操作数对应位有一个为0,则结果的对应位为0。(有0则0)

综上,一个位和1位与还是这个位,和0位与则是0;

一、基本应用:

#include 

int main() {
    unsigned int a = 60;   // 二进制表示为 0011 1100
    unsigned int b = 13;   // 二进制表示为 0000 1101
    unsigned int result = a & b;  // 二进制表示为 0000 1100

    printf("位与操作结果为:%u\n", result);
    return 0;
}
  • 这段代码中,我们定义了两个无符号整数变量 a 和 b,它们分别初始化为60和13。然后,我们使用位与操作符 & 对它们进行位与操作,并将结果赋值给变量 result。最后,我们使用printf函数打印出结果。

❤️上述代码的输出结果将为 12,这是因为60的二进制表示为 0011 1100,13的二进制表示为 0000 1101,两者进行位与操作后得到的结果为 0000 1100,即十进制的 12。

⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️
❗️注意一些不常见的输出方式:

  • %o:无符号8进制整数(不输出前缀0);
  • %u:无符号10进制整数;
  • %x(%X):无符号16进制,不输出前缀0x (小写x输出小写字母abcdef,大写X类似);
  • %d(%i):有符号10进制整数(i为老式写法);
  • %e(%E):科学计数法的形式输出 (小写e表示输出时用e,如2e-1;
  • %p:16进制形式输出指针
  • %g(G):在%e和%f中选择一种输出长度较短的输出。(G对应E)

⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️ ⭐ ⭐️


二、拓展应用:

1. 提取特定位的值:

❤️位与操作可以用于提取一个数字的特定位的值。通过与一个只有特定位为1的掩码进行位与操作,可以将其他位的值清零,从而提取出特定位的值。
提取特定位的值:

#include 

#define MASK (0x0F)  // 二进制表示为 0000 1111

int main() {
    unsigned int num = 0x3A;  // 二进制表示为 0011 1010
    //int num=0b00111010   //二进制数定义的一种方法
    unsigned int lowNibble = num & MASK;

    printf("Low nibble: 0x%X\n", lowNibble);
    return 0;
}

❤️ 在这个例子中,我们定义了一个宏 MASK,它的二进制表示为 0000 1111,用于提取一个数字的低4位。在 main 函数中,我们定义了一个变量 num,并使用位与操作将其与掩码 MASK 进行位与运算,从而提取出低4位的值。最后,我们使用 printf 函数打印出结果。

输出结果将为:

Low nibble: 0xA

小试牛刀:

二进制分类

题目描述

若将一个正整数化为二进制数,在此二进制数中,我们将数字 1 1 1 的个数多于数字 0 0 0 的个数的这类二进制数称为 A A A 类数,否则就称其为 B B B 类数。
例如:
( 13 ) 10 = ( 1101 ) 2 (13)_{10}=(1101)_2 (13)10=(1101)2,其中 1 1 1 的个数为 3 3 3 0 0 0 的个数为 1 1 1,则称此数为 A A A 类数;
( 10 ) 10 = ( 1010 ) 2 (10)_{10}=(1010)_2 (10)10=(1010)2,其中 1 1 1 的个数为 2 2 2 0 0 0 的个数也为 2 2 2,称此数为 B B B 类数;
( 24 ) 10 = ( 11000 ) 2 (24)_{10}=(11000)_2 (24)10=(11000)2,其中 1 1 1 的个数为 2 2 2 0 0 0 的个数为 3 3 3,则称此数为 B B B 类数;
程序要求:求出 1~n 之中( 1 ≤ n ≤ 1000 1 \le n \le 1000 1n1000),全部 A , B A,B A,B 两类数的个数。
输入格式
输入 n n n
输出格式
一行,包含两个整数,分别是 A A A 类数和 B B B 类数的个数,中间用单个空格隔开。
样例
样例输入

7

样例输出

5 2

很明显,我们只需要得到一个数的二进制表达,然后用眼睛一扫,就可以数出来0和1哪个多(xixi),但我们这里只有10进制表达,如果都转为2进制的话还是有麻烦。虽然 C++ 中提供了一种用于存储 0 和 1 的数据类型 bitset ,可以用于将一个数转换为二进制,但没有必要。我们只需要借助今天学习的位与+位移–>就可以轻松解决。

❤️位移分为左移和右移:
左移就是向左移(乘以2),在后面补0,比如:110—>1100;
右移就是向右移(不一定是除以2),比如:1101–>110;

#include

using namespace std;
int num_a, num_b;//分别代表A类和B类数

void recognize(int x)
{

	int sum;
	int sum_0=0, sum_1=0;//分别用来统计0和1的个数
	while (x > 0)
	{
		sum = x & 1;//得到末位
		if (sum == 0) sum_0++;
		else sum_1++;

		x=x >> 1;//右移一位,得到上一位
	}
	if (sum_1 > sum_0) num_a++;
	else num_b++;

}
int main(void)
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		recognize(i);
	}
	cout << num_a << " " << num_b;
	return 0;
}
  • 因题目过于简单,具体的解释我已经放在了注释中,不再过多说明。

拓展思考:

如何提取一个二进制数的末n位数呢❓

⭐️就比如拿10001110来说,我们要得到1110,那么最简单的方法就是让它和00001111位与,末4位–>与2^4-1位与。
⭐️相信聪明的你已经发现了,要想得到一个二进制数的末n位数,最简便的方法就是让它和2^n-1位与.
⭐️那问题又来了,怎么得到任意连续的位数呢❓ 其实这也不难想出,利用位移的思想即可转化为上面的问题。


2. 位掩码(Bitmasking):

❤️位掩码是一种使用位与操作来检查或设置特定位的值的技术。通过定义一些常量或宏来表示不同的位,可以使用位与操作来检查或设置特定位的值。例如,可以使用位与操作来检查一个数字的最低位是否为1,或者将某些位设置为0或1。

#include 

#define FLAG_A (1 << 0)  // 第0位为1 001
#define FLAG_B (1 << 1)  // 第1位为1 010
#define FLAG_C (1 << 2)  // 第2位为1 100

int main() {
    unsigned int flags = FLAG_A | FLAG_B;  // 设置第0位和第1位为1   011

    if (flags & FLAG_A) {
        printf("Flag A is set\n");
    }

    if (flags & FLAG_B) {
        printf("Flag B is set\n");
    }

    if (flags & FLAG_C) {
        printf("Flag C is set\n");
    } else {
        printf("Flag C is not set\n");
    }

    return 0;
}

❤️在这个例子中,我们使用位掩码来表示一组标志位。通过定义宏或常量,我们可以将不同的位与特定的含义关联起来。在 main 函数中,我们定义了一个 flags 变量,通过位或操作将 FLAG_A 和 FLAG_B 设置为1。然后,我们使用位与操作检查每个标志位的状态,并打印相应的消息。(位或明天会将,'|'中,有1必1,全0才0)

  • 输出结果将为:

Flag A is set
Flag B is set
Flag C is not set


3. 清零特定位:

❤️位与操作可以用于将一个数字的特定位清零。通过与一个只有特定位为0的掩码进行位与操作,可以将特定位的值清零,而保持其他位的值不变。

#include 
#define CLEAR_BIT(x, n) (x & (~(1 << n)))  //最终得到: 111...0...1

int main() {
    unsigned int num = 0x3A;  // 二进制表示为 0011 1010
    unsigned int clearedNum = CLEAR_BIT(num, 3);  // 将第3位清零
    printf("Cleared num: 0x%X\n", clearedNum);
    return 0;
}

❤️在这个例子中,我们定义了一个宏 CLEAR_BIT,它接受两个参数:一个数字 x 和一个位的索引 n。宏的作用是将数字 x 的第 n 位清零。在 main 函数中,我们定义了一个变量 num,并使用 CLEAR_BIT 宏将其第3位清零。最后,我们使用 printf 函数打印出结果。(~是按位取反的意思,0变1,1变0)

  • 输出结果将为:

Cleared num: 0x32


4. 判断奇偶性:

❤️相信大家对于判断一个数是奇数还是偶数并不陌生。

  • 常见的方法大概是这样的:
#include

using namespace std;

int main(void)
{
	int n;
	cin >> n;
	if(n%2==0)
		cout << "even" << endl;//偶数
	else
		cout << "odd" << endl;//奇数
	return 0;
}

❤️但其实位与操作可以用于判断一个数字的奇偶性。通过与一个只有最低位为1的掩码进行位与操作,如果结果为0,则表示该数字为偶数;如果结果为1,则表示该数字为奇数。原因在于如果一个数是偶数,那么它的二进制表示中末位不能是1(为啥啊?),也就是它和1位与是0;奇数则二进制表示中末位一定是1。

  • 进阶代码如下:
#include 

int main() {
    unsigned int num = 9;  // 二进制表示为 0000 1001

    if (num & 1) {
        printf("Number is odd\n");//奇数
    } else {
        printf("Number is even\n");//偶数
    }

    return 0;
}

❤️在这个例子中,我们定义了一个变量 num,它的二进制表示为 0000 1001。通过将 num 与1进行位与操作,我们可以判断最低位是否为1,从而判断数字的奇偶性。如果结果为1,则表示数字为奇数;如果结果为0,则表示数字为偶数。根据结果,我们打印相应的消息。

  • 输出结果将为:

Number is odd


三、思考题:

⭐️如何判断一个数是不是2的幂,怎么利用今天的知识来解决呢❓且听下回分解……


彩蛋:

好了,今天的讲解就到这里了,最后再放一个彩蛋:

❤️七夕节到了,想来一场浪漫的表白却又没有好方式的友友们看过来,别眨眼:

第6天----【位运算进阶之-----位与(&)】七夕特别版_第2张图片

想不想实现自己的爱心呢?想!怎么做呢?跟着我做!

  1. 首先创建一个txt文本(用记事本就行);
  2. 把下面的html代码复制进去;
  3. 将后缀改为.html即可;
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>真挚爱心TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <style>
  html, body {
  height: 100%;
  padding: 0;
  margin: 0;
  background: #000;
}
canvas {
  position: absolute;
  width: 100%;
  height: 100%;
}
  style>
 HEAD>

 <BODY>
  <canvas id="pinkboard">canvas>
  <script>
 
var settings = {
  particles: {
    length:   500, // maximum amount of particles
    duration:   2, // particle duration in sec
    velocity: 100, // particle velocity in pixels/sec
    effect: -0.75, // play with this for a nice effect
    size:      30, // particle size in pixels
  },
};


(function(){var b=0;var c=["ms","moz","webkit","o"];for(var a=0;a<c.length&&!window.requestAnimationFrame;++a){window.requestAnimationFrame=window[c[a]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[c[a]+"CancelAnimationFrame"]||window[c[a]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame){window.requestAnimationFrame=function(h,e){var d=new Date().getTime();var f=Math.max(0,16-(d-b));var g=window.setTimeout(function(){h(d+f)},f);b=d+f;return g}}if(!window.cancelAnimationFrame){window.cancelAnimationFrame=function(d){clearTimeout(d)}}}());


var Point = (function() {
  function Point(x, y) {
    this.x = (typeof x !== 'undefined') ? x : 0;
    this.y = (typeof y !== 'undefined') ? y : 0;
  }
  Point.prototype.clone = function() {
    return new Point(this.x, this.y);
  };
  Point.prototype.length = function(length) {
    if (typeof length == 'undefined')
      return Math.sqrt(this.x * this.x + this.y * this.y);
    this.normalize();
    this.x *= length;
    this.y *= length;
    return this;
  };
  Point.prototype.normalize = function() {
    var length = this.length();
    this.x /= length;
    this.y /= length;
    return this;
  };
  return Point;
})();


var Particle = (function() {
  function Particle() {
    this.position = new Point();
    this.velocity = new Point();
    this.acceleration = new Point();
    this.age = 0;
  }
  Particle.prototype.initialize = function(x, y, dx, dy) {
    this.position.x = x;
    this.position.y = y;
    this.velocity.x = dx;
    this.velocity.y = dy;
    this.acceleration.x = dx * settings.particles.effect;
    this.acceleration.y = dy * settings.particles.effect;
    this.age = 0;
  };
  Particle.prototype.update = function(deltaTime) {
    this.position.x += this.velocity.x * deltaTime;
    this.position.y += this.velocity.y * deltaTime;
    this.velocity.x += this.acceleration.x * deltaTime;
    this.velocity.y += this.acceleration.y * deltaTime;
    this.age += deltaTime;
  };
  Particle.prototype.draw = function(context, image) {
    function ease(t) {
      return (--t) * t * t + 1;
    }
    var size = image.width * ease(this.age / settings.particles.duration);
    context.globalAlpha = 1 - this.age / settings.particles.duration;
    context.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
  };
  return Particle;
})();


var ParticlePool = (function() {
  var particles,
      firstActive = 0,
      firstFree   = 0,
      duration    = settings.particles.duration;
  
  function ParticlePool(length) {
    // create and populate particle pool
    particles = new Array(length);
    for (var i = 0; i < particles.length; i++)
      particles[i] = new Particle();
  }
  ParticlePool.prototype.add = function(x, y, dx, dy) {
    particles[firstFree].initialize(x, y, dx, dy);
    
    // handle circular queue
    firstFree++;
    if (firstFree   == particles.length) firstFree   = 0;
    if (firstActive == firstFree       ) firstActive++;
    if (firstActive == particles.length) firstActive = 0;
  };
  ParticlePool.prototype.update = function(deltaTime) {
    var i;
    
    // update active particles
    if (firstActive < firstFree) {
      for (i = firstActive; i < firstFree; i++)
        particles[i].update(deltaTime);
    }
    if (firstFree < firstActive) {
      for (i = firstActive; i < particles.length; i++)
        particles[i].update(deltaTime);
      for (i = 0; i < firstFree; i++)
        particles[i].update(deltaTime);
    }
    
    // remove inactive particles
    while (particles[firstActive].age >= duration && firstActive != firstFree) {
      firstActive++;
      if (firstActive == particles.length) firstActive = 0;
    }
  };
  ParticlePool.prototype.draw = function(context, image) {
    // draw active particles
    if (firstActive < firstFree) {
      for (i = firstActive; i < firstFree; i++)
        particles[i].draw(context, image);
    }
    if (firstFree < firstActive) {
      for (i = firstActive; i < particles.length; i++)
        particles[i].draw(context, image);
      for (i = 0; i < firstFree; i++)
        particles[i].draw(context, image);
    }
  };
  return ParticlePool;
})();

(function(canvas) {
  var context = canvas.getContext('2d'),
      particles = new ParticlePool(settings.particles.length),
      particleRate = settings.particles.length / settings.particles.duration, // particles/sec
      time;
  
  // get point on heart with -PI <= t <= PI
  function pointOnHeart(t) {
    return new Point(
      160 * Math.pow(Math.sin(t), 3),
      130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25
    );
  }
  
  // creating the particle image using a dummy canvas
  var image = (function() {
    var canvas  = document.createElement('canvas'),
        context = canvas.getContext('2d');
    canvas.width  = settings.particles.size;
    canvas.height = settings.particles.size;
    // helper function to create the path
    function to(t) {
      var point = pointOnHeart(t);
      point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;
      point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;
      return point;
    }
    // create the path
    context.beginPath();
    var t = -Math.PI;
    var point = to(t);
    context.moveTo(point.x, point.y);
    while (t < Math.PI) {
      t += 0.01; // baby steps!
      point = to(t);
      context.lineTo(point.x, point.y);
    }
    context.closePath();
    // create the fill
    context.fillStyle = '#ea80b0';
    context.fill();
    // create the image
    var image = new Image();
    image.src = canvas.toDataURL();
    return image;
  })();
  
  // render that thing!
  function render() {
    // next animation frame
    requestAnimationFrame(render);
    
    // update time
    var newTime   = new Date().getTime() / 1000,
        deltaTime = newTime - (time || newTime);
    time = newTime;
    
    // clear canvas
    context.clearRect(0, 0, canvas.width, canvas.height);
    
    // create new particles
    var amount = particleRate * deltaTime;
    for (var i = 0; i < amount; i++) {
      var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
      var dir = pos.clone().length(settings.particles.velocity);
      particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
    }
    
    // update and draw particles
    particles.update(deltaTime);
    particles.draw(context, image);
  }
  
  // handle (re-)sizing of the canvas
  function onResize() {
    canvas.width  = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
  }
  window.onresize = onResize;
  
  // delay rendering bootstrap
  setTimeout(function() {
    onResize();
    render();
  }, 10);
})(document.getElementById('pinkboard'));
  script>
 BODY>
HTML>



⭐️七夕快乐!愿天下有情人终成眷属!⭐️
第6天----【位运算进阶之-----位与(&)】七夕特别版_第3张图片

你可能感兴趣的:(c++,c语言,算法,html,xhtml)