1. Write a function to return the number of 1's in the parameter binary,
such as: 15 0000 1111 4 1
program prototype:
int count_one_bits(unsigned int value)
{
// return the number of 1 bits
}
such as: 15 0000 1111 4 1
program prototype:
int count_one_bits(unsigned int value)
{
// return the number of 1 bits
}
#define _CRT_SECURE_NO_WARNINGS ch #include<stdio.h> #include<Windows.h> #include<math.h> #include<time.h> //Write a function to return the number of 1's in the parameter binary //For example: 15 0000 1111 4 1s //Program prototype: int count_one_bits(unsigned int value) { int i = 0; int count = 0; for (i = 0; i < 32; i++){ if (1 == ((value >> i) & 1)){ count++; } } return count; } int main(){ int value = 15; int ret = count_one_bits(value); printf("%d\n", ret); system("pause"); return 0; }
Running result: (Test case: if input 15, it should output 4)
2. Get all the even and odd bits in a binary sequence of numbers, and output the binary sequence respectively.
#define _CRT_SECURE_NO_WARNINGS ch #include<stdio.h> #include<Windows.h> #include<math.h> #include<time.h> //Get all the even and odd bits in a binary sequence of numbers, and output the binary sequence respectively. int main(){ int i = 0; int value = 15; for (i = 0; i < 32; i+=2){ printf("%d ", (value >> i) & 1); } printf("\n"); for (i = 1; i < 32; i += 2){ printf("%d ", (value >> i) & 1); } system("pause"); return 0; }
3. Print each bit of an integer. (recursive implementation)
#define _CRT_SECURE_NO_WARNINGS ch #include<stdio.h> #include<Windows.h> #include<math.h> #include<time.h> // Output each bit of an integer. (recursive) void print(int num){ if (num >9){ print(num/10); } printf("%d", num % 10); } int main(){ int num = 1234; print(num); system("pause"); return 0; }
4. Programming implementation:
How many bits are different in the binary representation of two int (32-bit) integers m and n?
Input example:
1999 2299
Output example: 7
How many bits are different in the binary representation of two int (32-bit) integers m and n?
Input example:
1999 2299
Output example: 7
#define _CRT_SECURE_NO_WARNINGS ch #include<stdio.h> #include<Windows.h> #include<math.h> #include<time.h> //Programming implementation: //How many bits are different in the binary representation of two int (32-bit) integers m and n? //input example: //1999 2299 //Example of output: 7 int main(){ int a = 1999; int b = 2299; int i = 0; int count = 0; for (i = 0; i < 32; i++){ if (1 == ((a >> i) & 1) ^ ((b >> i) & 1)){ count++; } } printf("%d", count); system("pause"); return 0; }
Experimental results: