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

Problem-solving idea: print the even and odd bits in the binary digits of an integer, you can perform a shift operation on the integer, and then 1perform the &operation with the shifted binary bit .

Bitwise &, if the same is 1, it is 1, and if the difference is 1, it is 0.

Such as:

//0000 0000 0000 0000 0000 0000 0000 0001
//0000 0000 0000 0000 0000 0000 1100 0111   199

Like this number, perform a shift operation on this number, and you can get the binary bit of this number every time you shift one bit. But what we need is to output the even and odd bits separately, so we need to shift two bits every time.

#include <stdio.h>
#include <Windows.h>
#pragma warning(disable:4996)
#include <time.h>
#include <stdlib.h>
void All1(int m);

int main()
{
    
    
	int x = 199;
	All1(x);
	return 0;
}

void All1(int m)
{
    
    
	int i = 0;
	i = 31;
	printf("二进制:");
	while (i >= 0)
	{
    
    
		printf("%d ", (m >> i) & 1);
		i--;
	}
	printf("\n奇数位:");
	for (i = 0; i <=30; i += 2)
	{
    
    
		printf("%d ", (m >> i) & 1);
	}
	printf("\n偶数位:");
	for (i = 1; i <= 31; i += 2)
	{
    
    
		printf("%d ", (m >> i) & 1);
	}
	printf("\n");
}

The output result is:
Insert picture description here
This is first shifted from the low position to the right, but this is not conducive to viewing, so a little optimization.
Shift the entire number first. The even-numbered bits are shifted by 31 bits for the first time, and subtracted by 2 each time. The odd-numbered bits are shifted by 30 bits for the first time and subtracted by 2 each time.

#include <stdio.h>
#include <Windows.h>
#pragma warning(disable:4996)
#include <time.h>
#include <stdlib.h>
void All(int m);

int main()
{
    
    
	int x = 199;
	All(x);
	return 0;
}

void All(int m)
{
    
    
	int i = 0;
	i = 31;
	printf("二进制:");
	while (i>=0)
	{
    
    
		printf("%d ", (m >> i) & 1);
		i--;
	}
	printf("\n奇数位:");
	for (i = 30; i >= 0; i -= 2)
	{
    
    
		printf("%d ", (m >> i) & 1);
	}
	printf("\n偶数位:");
	for (i = 31; i >= 1; i -= 2)
	{
    
    
		printf("%d ", (m >> i) & 1);
	}

}

The result is:
Insert picture description here

Guess you like

Origin blog.csdn.net/w903414/article/details/105749564