www.久久久久|狼友网站av天堂|精品国产无码a片|一级av色欲av|91在线播放视频|亚洲无码主播在线|国产精品草久在线|明星AV网站在线|污污内射久久一区|婷婷综合视频网站

當(dāng)前位置:首頁(yè) > 公眾號(hào)精選 > 嵌入式基地

位操作符的一些運(yùn)算小技巧

本文主要介紹一些會(huì)經(jīng)常使用到的位操作小技巧。

使用位操作符時(shí)有以下兩點(diǎn)需要注意

  • 進(jìn)行位運(yùn)算時(shí)數(shù)據(jù)全部是換算為二進(jìn)制的。

  • 位操作符只適用于整形變量,不適合浮點(diǎn)數(shù)變量。(本質(zhì)是由于兩者的數(shù)據(jù)存儲(chǔ)類型不同)

1. 交換兩個(gè)變量的值

int a = 1; int b = 2;
 a ^= b;
 b ^= a;
 a ^= b; printf("a: %d b: %d\n", a, b);

2. 求二進(jìn)制中1的個(gè)數(shù)

int a = 5; int count = 0; while (a) {
 a = a&(a - 1); //每次把最低位丟棄,直到a為0. count++;
} printf("%d\n", count);

3. 求二進(jìn)制中0的個(gè)數(shù)

int a = 5; int count = 0; while (a+1) {
 a = a | (a + 1);
 count++;
} printf("%d\n", count);

4. 求一個(gè)數(shù)的絕對(duì)值

int i = -2; int j = i >> 31;

i = (i ^ j) - j; printf("%d\n", i);

5. 求一個(gè)數(shù)的相反數(shù)

int i = -2;

i = ~i + 1; printf("%d\n", i);

6. 判斷一個(gè)數(shù)的奇偶性

int a = 3; if((a&1) == 1) { printf("奇數(shù)\n");
} else { printf("偶數(shù)\n");
}

7. 求兩個(gè)數(shù)的平均數(shù)

int a = 3; int b = 7; printf("平均值: %d\n", ((a + b) >> 1));

8. 從無(wú)符號(hào)類型x的第p位開始,取n位數(shù)

unsigned GetBits(unsigned x,int p, int n) { return (x>>(p+1-n)) & ~(~0<
		


本站聲明: 本文章由作者或相關(guān)機(jī)構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點(diǎn),本站亦不保證或承諾內(nèi)容真實(shí)性等。需要轉(zhuǎn)載請(qǐng)聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請(qǐng)及時(shí)聯(lián)系本站刪除。
關(guān)閉