UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » How to trans int to DEC string without division or complementation

#1 2009-04-29 01:58 AM

xinglp
Member
Registered: 2008-04-13
Posts: 35

Re: How to trans int to DEC string without division or complementation

I can do that with HEX string.

Thanks.

Offline

#2 2009-04-29 04:24 AM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: How to trans int to DEC string without division or complementation

void IntToStr(int val, char * b)
{
   if (val < 0)
   {
      b[0] = '-';
      IntToStr(-val, b+1);
   }
   else if (val == 0)
   {
      b[0] = '0';
      b[1] = '\0';
   }
   else
   {
      int i;
      int pos = 0;
      const int units[] = {1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1};
      bool hadValidDigit = false;
      for (i=0; i<(sizeof(units)/sizeof(units[0])); i++)
      {
         const int unit = units[i];
         int digit = 0;
         while(val >= unit)
         {
            digit++;
            val -= unit;
         }
         if (digit != 0) hadValidDigit = true;
         if (hadValidDigit) b[pos++] = (digit+'0');
      }
      b[pos] = '\0';
   }
}

Offline

#3 2009-04-29 04:27 AM

xinglp
Member
Registered: 2008-04-13
Posts: 35

Re: How to trans int to DEC string without division or complementation

Thanks a lot

Offline

  • Index
  • » C
  • » How to trans int to DEC string without division or complementation

Board footer

Powered by FluxBB