Several problems

Keywords: Programming

1. Write a function to return the number of 1 in the parameter binary
For example: 15,000,1111,4 1
Program prototype:
int count_one_bits(unsigned int value)
{
//Number of digits returned to 1
}
Solution:
The unsigned integer is 32 bits, so we use 32 cycles to judge whether each bit of binary is 1?

int   count_one_bits(unsigned int value)
{
  
    int i = 0;
    int count = 0;   //count
  for(i=0;i<32;i++){
       if( ((value>>i)&1)==1)
       count++
}
  }

2. Get all even and odd digits in a binary sequence.
Output binary sequence.

Solution: Similar to the previous question, loop 32 times to create two arrays, one for odd positions and one for even positions.

#include <stdio.h>
int main(){
 int i=0,j=0;
 char arr1[16];  //Define two arrays to store binary sequences
 char arr2[16];
 int num=0;
 scanf("%d",&num);
 for(i = 0; i < 32; i += 2)
 {
  arr1[j] = ((num >> i) & 1);  //Odd digit
  j++;
 }
 for(i = 1,j=0; i < 32; i += 2)
 {
  arr2[j] = ((num >> i) & 1);  //Even digit
  j++;
 }
 printf("The odd digits are:");  //Binary odd sequence in output array
 for (i = 15; i >= 0; i--)
 {
  printf("%d",arr1[i]);
 }
 printf("\n");
 printf("Even digits are:");//Binary Even Sequence in Output Array
 for (i = 15; i >= 0; i--)
 { 
  printf("%d",arr2[i]);
 }
 return 0;
} 
  1. Output each bit of an integer.
    Solution:
#include <stdio.h>
int main(){
 int i=0,j=0;
 char arr1[32];  
 
 int num=0;
 scanf("%d",&num);
 for(i = 0; i < 32; i ++)
 {
  arr1[j] = ((num >> i) & 1);  
  j++;
 }
 
 
 for (i = 31; i >= 0; i--)
 {
  printf("%d",arr1[i]);
 }
 printf("\n");
 
 return 0;
}

4. Programming:
How many bits are different in the binary representation of two int (32-bit) integers m and n?
Input examples:
1999 2299
Output examples: 7
Solution:

#include <stdio.h>
int main(){
 int i=0;
 int j=0;
 int a,b;  
 int num2=0;
 int num1=0;
 scanf("%d %d",&num1,&num2);
 
 for(i = 0; i < 32; i ++)
 {
  a=((num1 >> i) & 1);  
  
  b=((num2 >> i) & 1);
  if(a!=b){
   j++;}
 }
 printf("%d",j);
 
 
 
 return 0;
}

Posted by Moesian on Sat, 26 Jan 2019 22:03:14 -0800