0

So I have this function:

static void doPrint (const char *s)
{
    write (STDOUT_FILENO, s, strlen(s));
}

I am trying to pass it an unsigned long variable but nothing I have tried has worked so far. My question is, how do I go about doing this? I was thinking of using something along the lines of _ultoa_s or another similar function.

Any ideas? Thanks

Note: Access to printf, sprintf, ect is restricted

Pat
  • 649
  • 1
  • 8
  • 24

3 Answers3

0

You could try passing the pointer to long variable and the size to your doPrint function as below

doPrint((char *)(&someLongVariable), sizeof(someLongvariable));

void doPrint(char *inpString, int size)
{
     write (STDOUT_FILENO, inpString, size);
}
Ganesh
  • 5,880
  • 2
  • 36
  • 54
  • See my answer for why I have down voted this: the OP needs guidance on the big picture, not necessarily being strung along down the wrong path. – wallyk Feb 13 '13 at 23:40
0

Almost certainly you do not want to pass a double to this function. It expects text to output which is the convention of stdout.

Almost certainly, you first need to represent the double's value in characters and pass that to the function. This is a complex topic, and probably the point of the exercise. Google for "convert float to ascii" for some ideas of what you have to do.


Follow up:

If you are permitted to use _ultoa_s, then certainly you could call fcvt() or ecvt().

wallyk
  • 56,922
  • 16
  • 83
  • 148
0

You didn't mention whether "restricted" means that the easy functions (printf and friends) aren't available on your (embedded?) platform, or that this is a restriction of the assignment.

Anyways, what you are doing won't work, ever. You're passing in a binary variable (a long), it won't automagically get converted to a string.

Check out this function, found here, a compact itoa function. Some tweaking required to make an ltoa out of it, but it's easy to see how it works.

//return the length of result string. support only 10 radix for easy use and better performance
int my_itoa(int val, char* buf)
{
    const unsigned int radix = 10;

    char* p;
    unsigned int a;        //every digit
    int len;
    char* b;            //start of the digit char
    char temp;
    unsigned int u;

    p = buf;

    if (val < 0)
    {
        *p++ = '-';
        val = 0 - val;
    }
    u = (unsigned int)val;

    b = p;

    do
    {
        a = u % radix;
        u /= radix;

        *p++ = a + '0';

    } while (u > 0);

    len = (int)(p - buf);

    *p-- = 0;

    //swap
    do
    {
        temp = *p;
        *p = *b;
        *b = temp;
        --p;
        ++b;

    } while (b < p);

    return len;
}
fvu
  • 32,488
  • 6
  • 61
  • 79