C/C++/C#/JAVA/單晶片 位元運算 應用
C/C++/C#/JAVA/單晶片 位元運算 應用
資料來源: https://blog.kuoe0.tw/posts/2012/01/26/bitwise-operation-utlization/
01.奇數/偶數 判斷
if((x & 1) == 1)
{
}
else
{
}
02.利用左移運算,即可輕易將整數 x 乘以 2^n
x << n
03.利用右移運算,即可輕易將整數 x 除以 2^n
x >> n
04.末端連續 n 個位元 1
(1 << n) - 1
05.取 2^n 的模數
x & ((1 << n) - 1)
06.最低的位元 1
x & -x
07.是否為二的冪次(2的次方)
if((x & -x) == x)
{
}
else
{
}
08.將第 n 個位元設定為 0
x & ~(1 << n)
09.整數交換(SWAP)
x^=y^=x^=y
10.消去最低位 1 位元
x & ( x - 1 )
11.將第 n 個位元設定為 1
x | ( 1 << n )
測試範例
#include <stdio.h>
#include <stdlib.h>
void pause()
{
printf("Press Enter key to continue...");
fgetc(stdin);
}
int sky_itoa(int value, char *str, unsigned int radix)
{
char list[] = "0123456789ABCDEF";
unsigned int tmp_value;
int i, j, k;
if (NULL == str)
{
return 1;
}
if (2 != radix && 8 != radix && 10 != radix && 16 != radix)
{
return 1;
}
i = 0;
k = 0;
if (radix == 10 && value < 0) {
tmp_value = (unsigned int)(0 - value);
str[i++] = '-';
k = 1;
}
else
{
tmp_value = (unsigned int)value;
}
do
{
str[i++] = list[tmp_value%radix];
tmp_value /= radix;
} while(tmp_value);
str[i] = '\0';
//翻转
char tmp;
for (j = k; j < (i+k)/2; j++)
{
tmp = str[j];
str[j] = str[i+k-j-1];
str[i+k-j-1] = tmp;
}
return 0;
}
int main()
{
int x=10;
char str[100] ={0};
sky_itoa(x,str,2);
printf("%d=>%s\n",x,str);
str[0] ='\0';
if((x & 1) == 1)
{
printf("%d=>odd\n",x);
}
else
{
printf("%d=>even\n",x);
}
printf("%d*(2^3)=>%d\n",x,(x << 3));
printf("%d/(2^3)=>%d\n",x,(x >> 3));
str[0] ='\0';
sky_itoa((1 << 10) - 1,str,2);
printf("%s\n",str);
printf("%d\n",( x & ((1 << 3) - 1) ) );
printf("%d\n",(x & -x));
if((8 & -8) == 8)
//if((x & -x) == x)
{
printf("%c\n",'O');
}
else
{
printf("%c\n",'X');
}
printf("%d\n",(x & ~(1 << 3)));
printf("%d\n",(x | (1 << 2)));
pause();
return 0;
}