user1212697
user1212697

Reputation: 679

Division alg C to get floating point number

Hi I got this division alg to display the integer and floating point values. How can I get MAX_REM? it is supposed to be the size of the buffer where our characters are going to be stored, so the size has to be the # of digits, but I don't know how to get that. thanks!

void divisionAlg(unsigned int value)
{

    int MAX_BASE=10;
    const char *charTable = {"0123456789ABCDEF"};  // lookup table for converting remainders
    char rembuf[MAX_REM + 1];   // holds remainder(s) and provision null at the end
    int  index;                 // 
    int  i;                     // loop variable

    unsigned int rem;           // remainder
    unsigned int base;          // we'll be using base 10 
    ssize_t numWritten;         // holds number of bytes written from write() system call

    base = 10;

    // validate base
    if (base < 2 || base > MAX_BASE)
        err_sys("oops, the base is wrong");

    // For some reason, every time this method is called after the initial call, rembuf
    // is magically filled with a bunch of garbage; this just sets everything to null.
    // NOTE: memset() wasn't working either, so I have to use a stupid for-loop
    for (i=0; i<MAX_REM; i++)
        rembuf[i] = '\0';

    rembuf[MAX_REM] = 0;    // set last element to zero
    index = MAX_REM;        // start at the end of rembuf when adding in the remainders

    do
    {
        // calculate remainder and divide valueBuff by the base
        rem = value % base;
        value /= base;

        // convert remainder into ASCII value via lookup table and store in buffer
        index--;
        rembuf[index] = charTable[rem];

    } while (value != 0);

    // display value
    if ((numWritten = write(STDOUT_FILENO, rembuf, MAX_REM + 1)) == -1)
        err_sys("something went wrong with the write");

} // end of divisionAlg()

Upvotes: 1

Views: 294

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129364

The calculation for figuring out how many digits there are a number takes is:

digits = floor(log(number)/log(base))+1;

However, in this case, I'd probably just assume the worse case, since it's no more than 32, and calculating it will be "expensive". So just #define MAX_REM 32, and then keep track of how many digits you actually put into rembuf (you already have index for that, so it's no extra cost really). You'll obviously need to calculate the amount of bytes to write out as well, but shouldn't require any special math.

Upvotes: 2

Related Questions