Function uses mask, bitwise operator and shift operator to determine bits (as op
ID: 3889577 • Letter: F
Question
Function uses mask, bitwise operator and shift operator to determine bits (as opposed to integer modulus and integer division)
Write a function accepts an unsigned short sized integer value and an array of unsigned char sized integer values. The function places each of the 16 bits of unsigned short integer into different array elements, in the least significant bit location. If, for example, the input integer was 25 ( 0x0019 = 0b000000000001 1001 ) then the array would need to contain The function prototype (or signature) is: void toBits (unsigned short value, unsigned char inBits [SIZE INT]);Explanation / Answer
#include<stdio.h>
#include<conio.h>
void toBits(unsigned int,unsigned char[]); // Prototype Declaration
void main()
{
unsigned int num;
unsigned char inBits[16];
printf("Enter Decimal Number : ");
scanf("%u",&num);
toBits(num,inBits); // Function Call
getch();
}
//========================================================
void toBits(unsigned int num,unsigned char inBits[])
{
int i=0;
int j=0;
unsigned int mask=32768; //mask = [1000 0000 0000 0000]
printf("Binary Eqivalent : ");
while(mask > 0)
{
if((num & mask) == 0 ){
inBits[i++]=48;
}
else{
inBits[i++]=49;
}
mask = mask >> 1 ; // Right Shift
}
printf(" ");
for(j=0;j<16;j++)
printf("%c",inBits[j]);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.