Print the odd and even digits of a binary digit

Table of Contents of Series Articles


Preface

Mainly learn the binary output method

1. Question:
Get all the even and odd bits in an integer binary sequence and print out the binary sequence respectively.

Analysis:
Print the even digits and odd digits in the binary digits of an integer. You can perform a shift operation on the integer (reverse printing), and then print the shifted binary digits. Perform & operation with 1,

Case 1

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	printf("2进制:\n");
	for (int i = 32; i >= 0; i--) {
    
    
		printf("%d ", (n >> i) & 1);
		//反向打印
	}
	printf("\n奇数位:\n");
	for (int i = 31; i >= 0; i -= 2) {
    
    
		printf("%d ", (n >> i) & 1);
	
	}
	printf("\n偶数位:\n");
	for (int i = 32; i > 0; i -= 2) {
    
    
		printf("%d ", (n >> i) & 1);

	}
	return 0;
}

Output result:
Insert image description here

Insert image description here

Case 2

#include<stdio.h>
void Print(int n)
{
    
    
	int i = 31;
	printf("二进制位:");
	while (i >= 0)
	{
    
    
		printf("%d ", (n >> i) & 1);
		i--;  //此处是使结果正向打印
	}
	printf("\n");
	printf("奇数位:");
	for (i = 30; i >= 0; i-=2)  //此处是使结果正向打印
	{
    
    
		printf("%d ", (n >> i) & 1);
	}
	printf("\n");
	printf("偶数位:");
	for (i = 31; i >= 1; i -= 2)  //此处是使结果正向打印
	{
    
    
		printf("%d ", (n >> i) & 1);
	}
	printf("\n");
}
int main()  //获取一个整数二进制序列中所有的偶数位和奇数位,分别打印出二进制序列
{
    
    
	int a = 0;
	scanf("%d", &a);
	Print(a);
    return 0;
}

Output result:
Insert image description here

Guess you like

Origin blog.csdn.net/chendemingxxx/article/details/134323017