How to convert a 128-bit integer to a decimal ascii string in C?

前端 未结 7 2192
小蘑菇
小蘑菇 2020-12-14 10:44

I\'m trying to convert a 128-bit unsigned integer stored as an array of 4 unsigned ints to the decimal string representation in C:

unsigned int src[] = { 0x1         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-14 11:24

    Straightforward division base 2^32, prints decimal digits in reverse order, uses 64-bit arithmetic, complexity O(n) where n is the number of decimal digits in the representation:

    #include 
    
    unsigned int a [] = { 0x12345678, 0x12345678, 0x12345678, 0x12345678 };
    
    /* 24197857161011715162171839636988778104 */
    
    int
    main ()
    {
      unsigned long long d, r;
    
      do
        {
          r = a [0];
    
          d = r / 10;
          r = ((r - d * 10) << 32) + a [1];
          a [0] = d;
    
          d = r / 10;
          r = ((r - d * 10) << 32) + a [2];
          a [1] = d;
    
          d = r / 10;
          r = ((r - d * 10) << 32) + a [3];
          a [2] = d;
    
          d = r / 10;
          r = r - d * 10;
          a [3] = d;
    
          printf ("%d\n", (unsigned int) r);
        }
      while (a[0] || a[1] || a[2] || a[3]);
    
      return 0;
    }
    

    EDIT: Corrected the loop so it displays a 0 if the array a contains only zeros. Also, the array is read left to right, a[0] is most-significant, a[3] is least significant digits.

提交回复
热议问题