2

逍遥自在学C语言 位运算符 "|" 的5种高级用法 - 知微之见

 1 year ago
source link: https://www.cnblogs.com/Wayne123/p/17308307.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在上一篇文章中,我们介绍了&运算符的高级用法,本篇文章,我们将介绍| 运算符的一些高级用法。

1511464-20230411232910387-1595135366.png

一、人物简介

  • 第一位闪亮登场,有请今后会一直教我们C语言的老师 —— 自在。
1511464-20230403100945222-934948634.gif
  • 第二位上场的是和我们一起学习的小白程序猿 —— 逍遥。
1511464-20230403101030223-1500558355.gif

二、将两个字节合并成一个16位整数

#include <stdio.h>

int main() 
{
    unsigned char lowByte = 0x12;   // 0001 0010
    unsigned char highByte = 0x34;  // 0011 0100
    unsigned short result = (highByte << 8) | lowByte;  // 0011 0100 0001 0010
    printf("合并结果为 %04x\n", result);       // 输出: 0x3412
    return 0;
}
1511464-20230411232922686-741785146.png

三、将一个字节的低4位和高4位交换

#include <stdio.h>

int main() 
{
    unsigned char data = 0xab;   // 1010 1011
    data = (data << 4) | (data >> 4);  // 1011 1010
    printf("交换结果为 %02x\n", data);      // 输出:0xba
    return 0;
}
1511464-20230411232931427-134046430.png

四、将一个字节中的某些位置1

#include <stdio.h>
int main() 
{
    int x;
    printf("请输入一个数:");
    scanf("%d", &x);
    printf("\n第4位置1后,这个数变为 %d\n", x | 0b1000); 
    return 0;
}
1511464-20230411232940764-1372967248.png

五、将一个字节中的某些位置0

#include <stdio.h>
int main() {
    int x;
    int a = 0b1000; 
    printf("请输入一个数:");
    scanf("%d", &x);
    printf("\n第4位置0后,这个数变为 %d\n", (x | a) - a ); 
    return 0;
}
1511464-20230411232949228-66080845.png

六、将低位连续的0变为1

#include <stdio.h>
int main() 
{
    int x;
    printf("请输入一个数:");
    scanf("%d", &x);
    printf("\n低位连续的0变为1,这个数变为%d\n", x | (x-1) );
    return 0;
}
1511464-20230411233010329-992632143.png
1511464-20230411233015983-424782580.gif

通过这篇文章,我们学会了用位运算符|的5种高级用法

​ 1、将两个字节合并成一个16位整数

​ 2、将一个字节的低4位和高4位交换

​ 3、将一个字节中的某些位置1

​ 4、将一个字节中的某些位置0

​ 5、将低位连续的0变为1

在下一篇文章中,我们将介绍位运算符^的一些高级用法。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK