DanielJohnson wrote:
>> You're on the trail of the problem. See Question 7.5a in
>> the comp.lang.c Frequently Asked Questions (FAQ) list at
>> <http://www.c-faq.com/>.
>>
>> --
>> Eric Sosman
>> esos...@ieee-dot-org.invalid
>
> Thanks for quick pointer to the right place and my bad that I did not
> look it up before posting.
>
> By using static retval and malloc(), I can overcome the problem.
>
> A quick question, how can I initialize value using malloc(). For
> example, following is not valid.
>
> char *retval = malloc(CHAR_BIT + 1);
> retval = "00000000\0";
>
> Is there a terse way of doing it ? I know I could do in a for loop by
> assigning retval[i] a value of '0' each time. I wanted to learn a
> smarter way.
The character most easily overlooked is the rightmost,
where you must deposit a '\0'. In your code, this would be
most easily done by changing the calculation of `j' and
adding one line:
int i, j = sizeof(a)* CHAR_BIT; /* -1 removed */
retval[j--] = '\0'; /* added */
For the remaining digits, you could add an `else' to
your existing `if':
if (a & mask)
retval[j] = '1';
else /* added */
retval[j] = '0'; /* added */
Alternatively, you could use the ternary operator:
retval[j] = (a & mask) ? '1' : '0';
A slightly briefer and trickier way would be:
retval[j] = '1' - !(a & mask);
Finally, you might consider getting rid of `mask':
instead of shifting it successively to the left, consider
shifting `a' rightward so the bits slide successively into
the ones' place. Then you could write
retval[j] = '0' + (a & 1);
This last suggestion has a flaw: right-shifting a negative
value gives an implementation-defined result. But you've
already chosen to ignore what happens when you try to store
the value 128 in `mask' (whose maximum is only 127), so I
suspect you'd be willing to take your chances on the shift,
too.
--
Eric Sosman
lid