Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable leading zeroes in C99 printf

Tags:

c

printf

I'm writing a Multiprecision Library in C99. Depending on which platform my code is compiled I am selecting a different Base of representation.

So, for instance, let's say that on platform X the system select BASE=100; and on platform Y BASE=10000;

Let's say I'm representing big unsigned int as follow:

typedef struct a {
       big_enough_uint *digits;
       unsigned int length;
       unsigned int last;
} bigUint;

So when i'm on BASE-100 system I want my print function to be

void my_print(bigUint *A){
     unsigned int i=0;

     fprintf(stdout,"%d",A->digits[0]);
     if(i!= A->last){
          for(;i<=A->last;i++)
                fprintf(stdout,"%02d",A->digits[i]);
     }
     printf(stdout,"\n");
}

While on BASE-10000 systems I want it to be something like

void my_print(bigUint *A){
     unsigned int i=0;

     fprintf(stdout,"%d",A->digits[0]);
     if(i!= A->last){
          for(;i<=A->last;i++)
                fprintf(stdout,"%04d",A->digits[i]);
     }
     printf(stdout,"\n");
}

Why i want to do so??

Let's say i have the following number:

12345600026789

In BASE-100 representation the digits array will be (little-endian form):

12|34|56|0|2|67|89
         ^ ^ I want ONE LEADING ZEROES

while in BASE-10000:

12|3456|2|6789
        ^ I want THREE LEADING ZEROES

Is there a simple way to do that?

like image 760
Alessandro L. Avatar asked Oct 27 '12 13:10

Alessandro L.


1 Answers

Read about the * place holder for the field width in man printf.

printf("%0*d", 3, 42);

gives

042

and

printf("% *s", 42, "alk");

gives

<39 spaces>alk
like image 118
alk Avatar answered Nov 05 '22 08:11

alk