/* gcc -m32 -c lab38main.c nasm -f elf32 -o lab38.o lab38.asm -I/usr/local/3304/include/ gcc -m32 -o lab38 lab38main.o lab38.o /usr/local/3304/src/Along32.o -lm ./lab38 < 01.dat */ #include #include #include // PrintBinary is a recursive assembly-language function that writes // the binary (base 2) representation of n to stdout void PrintBinary(int n); // PrintOctal is a recursive assembly-language function that writes // the octal (base 8) representation of n to stdout void PrintOctal(int n); // PrintHexadecimal is a recursive assembly-language function that writes // the hexadecimal (base 16) representation of n to stdout void PrintHexadecimal(int n); int main() { int n, bases[] = {2,8,16}; char hrule[74]; // declare an array of pointers, each element containing the address // of a function void (*func[])(int) = {&PrintBinary, &PrintOctal, &PrintHexadecimal}; // Initialize hrule to contain hyphens for (char *ptr = hrule; ptr < hrule + sizeof(hrule) - 1; ++ptr) *ptr = '-'; *(hrule + sizeof(hrule) - 1) = '\0'; // print the table heading printf("%s\n",hrule); printf(" Decimal "); printf(" Binary "); printf(" Octal "); printf("Hexadecimal\n"); printf("%s\n",hrule); // read an unknown # of ints from stdin; input terminates when the // end-of-data marker is encountered while (scanf("%d", &n) == 1) { printf(" %11d", n); // Loop to call each of the assembly-language functions for (int i = 0; i < sizeof(func) / sizeof(func[0]); ++i) { printf(" "); if (bases[i] == 16) printf(" "); // For the given base, determine the power of 2. For example, // if base = 2, the power of 2 is 1; if base = 8, the power // of 2 is 3; and so on. To compute this, take the base_2 log // of the base. int powerOf2 = (int) log2(bases[i]); // Calculate how many bits are in the internal representation // of an int. Then divide by the power of 2 to determine the // number of groupings that will be printed. If the division // process yields a remainder, increase the # of groups by 1. int width = sizeof(int) * CHAR_BIT / powerOf2; width += (sizeof(int) * CHAR_BIT % powerOf2) ? 1 : 0; // For positive ints, determine the # of digits needed to // display n in base[i]. Determine this by computing the // base[i] log of n. Truncate the logarithm and add 1. if (n > 0) width -= ((int) (log2((double) n) / log2(bases[i])) + 1); // For non-negative n, insert the appropriate # of leading 0s if (n >= 0) for (int j = 0; j < width; ++j) printf("0"); // Empty all non-empty output buffers before calling any of the // assembly functions. fflush(0); // For non-zero input values, call the assembly-language function, // passing n on the system stack. if (n != 0) (*func[i])(n); } printf("\n"); } printf("%s\n",hrule); return 0; }