Variable leading zeros in C99 printf

I am writing a Multiprecision library on C99. Depending on which platform is compiling, I choose a different view base.

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

Let's say I represent a large unsigned int as follows:

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

Therefore, when I am in the 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 a BASE-10000 system 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 do I want to do this?

Let's say I have the following number:

 12345600026789 

In the BASE-100 view, the array of numbers will be (little-endian form):

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

and in BASE-10000:

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

Is there an easy way to do this?

+4
source share
1 answer

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

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

gives

 042 

and

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

gives

 <39 spaces>alk 
+6
source

Source: https://habr.com/ru/post/1442485/


All Articles