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 ?
To print in base N, you need to make three changes:
- Instead of dividing by 10 the in the second line, divide by N
- Instead of doing mod 10 in the third line, do mod base N
- 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.
- Your original code forget to deal with negative numbers.
- This function works up to base 36. If you want even larger bases, you'll need to extend the
char c = ...
line.
精彩评论