writes:
> Hi All,
> I wrote the following to convert an integer to its string
> representation from base -32 to 32(32 since strtoul takes 32).
(You've already corrected this to 36 in another article.)
> Used recursion so as not to crowd the logic.
> Please Comment on this code.
> Posting from google groups.hope it dont end up in many expert's kill
> file.
Have you checked the results of your program? They're completely
wrong. A in base -10 should be identical to -(A in base 10).
> #include <stdio.h>
> #include <stdlib.h>
>
> char charTable[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
>
> void print(int i,int base)
> {
> if (i == 0)return;
> if (i%base >= 0)
> {
> print(i / base, base);
> printf("%c",charTable[i % base]);
> } else {
> print(i / base + 1, base);
> printf("%c",charTable[i % base - base]);
> }
print(i / base, base); in both cases, and charTable[abs(i % base)].
> }
>
> void printBase(int i,int base)
> {
> if ((abs(base) <= 1) || (abs(base) > 32) || (i == 0))
> {
> printf("0\n");
> return;
> }
I'm not certain you should print 0 for bad bases: I would print out
something that calls attention to the abuse of the function. In some
situations, I might use an assert() for this: for others, I'd probably
print something like "#ERR".
Also, you should really use something other than a magic number for
"32". You've already had to change this stuff once: what would've
happened if you'd forgotten to change the number above? If you use
(sizeof charTable) - 1
then you'll never have to mess with it again. (you could remove the "-
1" part if you use >= instead of >.)
>
> if ((base > 0) && (i < 0))
> {
> printf("-");
> i = -i;
> }
Great. But what if base < 0 and i > 0?
I think you want (base > 0) == (i < 0). And the inside will need some
modification (remove the i = -i).
> print(i, base);
> printf("\n");
> }
>
> int main(void)
> {
> int i;
> for(i = -55; i <= 55; i++)
> {
> printf("%3d = ", i);
> printBase(i,-10);
> }
> return 0;
> }
>
> Thanks and Regards,
> manoj.