Write a function printBinary() that displays the number of bits used VB2010. Usi
ID: 1922620 • Letter: W
Question
Write a function printBinary() that displays the number of bits used VB2010. Using 'sizeof()' if the user enters and int 17 the function should display 000000000000000000000000000010001.1- Initialize and unsigned int variable mask, with a value whose binary representation has a 1 followed by zeros.
2- For a counter running from 1 thru the number of bits
a. If the bitwise-and (&) of the given integer and mask is non zero: Display 1
Else Display 0
b. Shift the bits in mask one position to the right using >>.
Explanation / Answer
#include <iostream>
using namespace std;
char * printBinary (unsigned int val, char *buff, int sz) {
char *pbuff = buff;
/* Must be able to store one character at least. */
if (sz < 1) return NULL;
/* Special case for zero to ensure some output. */
if (val == 0) {
*pbuff++ = '0';
*pbuff = '';
return buff;
}
/* Work from the end of the buffer back. */
pbuff += sz;
*pbuff-- = '';
/* For each bit (going backwards) store character. */
while (val != 0) {
if (sz-- == 0) return NULL;
*pbuff-- = ((val & 1) == 1) ? '1' : '0';
/* Get next bit. */
val >>= 1;
}
return pbuff+1;
}
#define SZ 32
int main(int argc, char *argv[]) {
int i;
int n;
char buff[SZ+1];
n = 17;
cout<<" " << n <<" -> "<< printBinary(n,buff,SZ)<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.