Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of the following statements are correct about the program?

#include <stdio.h>
char *fun(unsigned int num, int base);

int main()
{
    char *s;
    s=fun(128, 2);
    s=fun(128, 16);
    printf("%s\n",s);
    return 0;
}
char *fun(unsigned int num, int base)
{
    static char buff[33];
    char *ptr = &buff[sizeof(buff)-1];
    *ptr = '\0';
    do
    {
        *--ptr = "0123456789abcdef"[num % base];
        num /=base;
    }while(num!=0);
    return ptr;
}

 

  • A.It converts a number to a given base.
  • B.It converts a number to its equivalent binary.
  • C.It converts a number to its equivalent hexadecimal.
  • D.It converts a number to its equivalent octal.

Answer: A

Correct answer: It converts a number to a given base.

The function is a general base converter. It builds the string backwards from the end of the buffer, taking num % base as the next digit, looking that digit up in "0123456789abcdef", and dividing num by base until nothing remains.

Because both the digit table and the divisor come from the base parameter, it handles any base up to 16 - binary and hexadecimal are merely the two the caller happens to use. The do...while form guarantees at least one digit, so an input of zero yields "0" rather than an empty string.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.