开发者

Printing Binary(byte) value in File

开发者 https://www.devze.com 2022-12-15 13:33 出处:网络
the below code print the biginteger to a file in decimal format ,how do i convert the code into printing binary data and hex datainto the File instead ??

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:

  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.
0

精彩评论

暂无评论...
验证码 换一张
取 消