Binary numbers,
Any number bitwise ANDed with N ones results in itself; or ORed with N zeros results in itself.
Any number bitwise ANDed with N zeros results in N zeros; any number bitwise ORed with N ones results in N ones.
Bitwise ANDing with N ones.
1 0 1 0 1 1 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 0 1 0 1 1 0 1 1 1 1
This property can be used to obtain certain bits of a number.
Obtain digits at certain positions
For example, to get the bits from positions 8 to 11 of an int type.
C# version
int num, mark;
Console.WriteLine("输入一个整数(大于256)");
num = Convert.ToInt32(Console.ReadLine());
num = num >> 8;
mark = ~(~0 << 4); // Construct 00000000 00000000 00000000 00001111
// mark = 0b00000000_00000000_00000000_00001111;
num = num & mark;
Console.WriteLine(num);
Console.ReadKey();
C version
#include <stdio.h>
int main()
{
printf("输入数字(256以上)");
int num;
int mark;
scanf("%d", &num);
num = num >> 8; /* Shift right by 8 bits to make bits 8-11 into bits 0-4 */
mark = num & ~(0 << 4);
printf("result = 0x%x", mark);
return(0);
}
Output a number's binary
The principle is that 0 or 1 bitwise ANDed with 1 equals itself, and bitwise ANDed with 0 equals 0.
Given any positive integer input, output the binary form of that number.
C version
#include <stdio.h>
int main()
{
printf("输入数字(256以上)");
int num;
int mark;
printf("%d", '1');
scanf("%d", &num);
mark = 1 << 31;
int i = 0;
for (i = 0; i <= 31; i++)
{
printf("%c", num & mark ? '1' : '0'); /* The result must either be greater than 0 or equal to 0 */
/* putchar(num & mark ? '1' : '0'); /* Force conversion to 8-bit variable (lower 8 bits) */ */
num = num << 1;
if ((i + 1) % 8 == 0)
putchar(',');
}
putwchar('B');
return(0);
}
C# version
uint num;
int mark;
Console.WriteLine("输入一个整数(大于256)");
num = Convert.ToUInt32(Console.ReadLine());
mark = 1 << 31;
string str = string.Empty;
for (int i = 0; i < 31; i++)
{
Console.Write((num & mark) == 0 ? '0' : '1'); // The result at each step should either be 1 or 0,
// the result must either be greater than 0 or equal to 0
num = num << 1;
if ((i + 1) % 8 == 0)
Console.Write(',');
}
Console.Write("B");
Console.ReadKey();
文章评论