Get all the even and odd bits in an integer binary sequence, and print out the binary sequence respectively

Ideas:

  1. Extract all odd bits, if the bit is 1, output 1, and if it is 0, output 0
  2. Extract the even position in the same way

Ways to detect whether a bit in num is 0 or 1:

  1. Move num to the right by i bits
  2. The result after the shift is bitwise AND with 1, if: the
    result is 0, the i-th bit is 0 and the
    result is non-zero, then the i-th bit is 1
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void Printbit(int num)
{
    
    
	for (int i = 31; i >= 1; i -= 2)
	{
    
    
		printf("%d ", (num >> i) & 1);
	}
	printf("\n");
	for (int i = 30; i >= 0; i -= 2)
	{
    
    
		printf("%d ", (num >> i) & 1);
	}
	printf("\n");
}
int main()
{
    
    
	int num = 0;
	printf("请输入一个数: ");
	scanf("%d", &num);
	Printbit(num);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/108590034