Part II: Submit a working code and sample outputs of your program 1. Write a C f
ID: 3723689 • Letter: P
Question
Part II: Submit a working code and sample outputs of your program 1. Write a C function that prints a number in binary on the screen. Assume the number N is passed as an argument to the function, and is of type integer (32 bits). Test your code! 2. Write a C function counts the number of ones (1) in an integer variable N passed as an argument to the function, while testing your code, you may use the place holder %X to display the integer number in hexadecimal Note: Write both functions in one single file and perform different tests on numbers entered by the user. Try also negative numbers! 3. Given the following operation: X = 41.Y + A and assuming the variables X, Y and A integer variables, do the following: a. Using the multiplication instructions, write a C code that performs the above task. b. Now, without using the multiplication instruction, write a C code that uses left and right shifts and addition or subtraction to perform the same task. Note: Write part b as a function that accepts A and Y as inputs and returns X.Explanation / Answer
a)Code to Convert Decimal to Binary
b) Program to count no. of 1 in binary representation of a number
#include <stdio.h>
/* Function to get no of set bits in binary
representation of positive integer n */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
return 0;
}
c)
#include <stdio.h>
int multiplyshift(int n, int m)
{
int ans = 0, count = 0;
while (m)
{
// check for set bit and left
// shift n, count times
if (m % 2 == 1)
ans += n << count;
// increment of place value (count)
count++;
m /= 2;
}
return ans;
}
int main()
{
int y,a;
printf( "Enter the values of Y and A :");
scanf("%d %d", &y, &a);
int x = 41*y + a;
printf("The multiplication normal is: "+x);
int mul = multiplyshift(41,y);
int ans = mul + a;
printf("The multiplication using shift operation is: "+ans);
return 0;
}
#include <stdio.h>
/* Function to get no of set bits in binary
representation of positive integer n */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
return 0;
}
c)
#include <stdio.h>
int multiplyshift(int n, int m)
{
int ans = 0, count = 0;
while (m)
{
// check for set bit and left
// shift n, count times
if (m % 2 == 1)
ans += n << count;
// increment of place value (count)
count++;
m /= 2;
}
return ans;
}
int main()
{
int y,a;
printf( "Enter the values of Y and A :");
scanf("%d %d", &y, &a);
int x = 41*y + a;
printf("The multiplication normal is: "+x);
int mul = multiplyshift(41,y);
int ans = mul + a;
printf("The multiplication using shift operation is: "+ans);
return 0;
}