Question

the below code print the biginteger to a file in decimal format ,how do i convert the code into printing binary data and hex data into the File instead ??

static void
print_pos( FILE* f, bigint bi )
{
    if ( bi_compare( bi_copy( bi ), bi_10 ) >= 0 )
        print_pos( f, bi_int_divide( bi_copy( bi ), 10 ) );
    putc( bi_int_mod( bi, 10 ) + '0', f );
}

bi_10 is just a type of bigint , how do i modify the above code to print the hex / binary data instead of decimal data ?

Was it helpful?

Solution

To print in base N, you need to make three changes:

  1. Instead of dividing by 10 the in the second line, divide by N
  2. Instead of doing mod 10 in the third line, do mod base N
  3. You will need to convert the the module from line 2 into the appropriate character. If you are doing base > 10, you will need to do an if/else

Here's what it would look like using plain integers. I'll let you make the appropriate changes to use your big int library:

static void
print_pos( FILE* f, int n, int base )
{
    if (n < 0)
    {
        n *= -1;
        putc( '-', f );
    }

    if (n >= base)
        print_pos( f, n / base, base );

    int d = n % base;
    const char *digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    putc( digits[d], f );
}

A couple of last comments.

  1. Your original code forget to deal with negative numbers.
  2. This function works up to base 36. If you want even larger bases, you'll need to extend the char c = ... line.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top