This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Fast Binary to Decimal code



SA

I need a fast  signed binary to decimal c code.

 

Thanks alot

  • Rammy,

    Have you tried the standard C library itoa() function?

    I have not compared its speed with other methods, but that would be a good place to start.

    How many decimal digits do you need, and what size of binary input do you need?  (32-bit, 64-bit, etc)

    Steve

  • Thanks for your reply

    I'd like to convert a 16 bit binary number to a decimal number ,i'll use this code with ccs  v4.2.1.

    I think that ccs doesn't have the itoa fn.

     

    Thanks alot

  • Ramy,

    You can pass this routine a 16-bit signed int, and the compiler will type cast it up to a 32-bit int.

    char  *itoa(int value, char *dest_p)
    {

        char      buffer[20];
        char     *p;
        int        x, y, n;

        x = value;
        if (value < 0)
            x = -x;

        buffer[19] = 0;
        p = &buffer[18];

        n = 1;
        do
          {
            y = x % 10;   // Modulo 10 to get next digit
            x /= 10;
            *p-- = (char) (y + 0x30);  // Convert to ASCII char
            n++;   // Count the digits produced
          }
        while (x);  // Repeat until x goes to zero

        if (value < 0)  // If the input was negative ...
          {
            *p-- = '-';  // Add a minus sign to the string
            n++;
          }

        // Copy string to destination area
        memcpy(dest_p, p + 1, n);

        return dest_p;

    }

  • Ramy,

    Ooops!

    x, y, and n should be 'unsigned int' types, to avoid problems when the input value is -2,147,483,648.

    Steve