<> subject

Gets all even and odd bits in an integer binary sequence , Print out the binary sequence separately

<> Thinking analysis

Prints the even and odd bits in the binary bits of an integer , You can shift integers , The shifted binary bits are then combined with the 1 conduct & operation . Binary sequences are stored in the computer 32 position , So without considering the sign bit of negative number , The odd and even digits are 16 individual . The odd and even numbers are discussed respectively ~~

<> code implementation

1. Method 1 Implementation of shift right operator
Shift right operator , The highest bit is the complement sign bit , But this question does not affect , Because in the loop , He is the lowest judge every time , In some questions , Shift right operator Be sure to use it with care ~ If you are not careful, there will be problems
int main() { int num = 0; printf(" Please enter a number :"); scanf("%d", &num); printf(" Odd number ：");
for (int i = 31; i >= 1; i -= 2) { printf("%d ", (num >> i) & 1); } printf("\n")
; printf(" Even digit ："); for (int i = 30; i >= 0; i -= 2) { printf("%d ", (num >> i) &
1); } printf("\n"); system("pause"); return 0; }
Straight to the top , It's clearer and more intuitive ~~
Even bits are the same as odd bits , It's a loop variable i It's different , Refer to the explanation of odd number ~

2. Method 2 Implementation of shift left operator
int main() { int num = 0; printf(" Please enter a number :"); scanf("%d", &num); printf(" Odd number ：");
for (int i = 31; i >= 1; i -= 2) { if (num & (1 << i)) { printf("%d ",1); } else
{ printf("%d ", 0); } } printf("\n"); printf(" Even digit ："); for (int i = 30; i >= 0; i
-= 2) { if (num & (1 << i)) { printf("%d ", 1); } else { printf("%d ", 0); } }
printf("\n"); system("pause"); return 0; }

Truth and right shift operator It's all the same ~ Just understand the shift left operator , Shift right operator , According to the principle of bit and, it's OK ~

Technology
Daily Recommendation
views 4