Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Convert any number to any base in C

Published on Tuesday, 31st August 2010.

I've just had a crack at Exercise 3-5. This is the first time too that I have used exit(). Usually I have been returning -1 for an error, or similar. The problem with that however, is the function's return type must be an int. This means, semantically, it would seem the function may be returning an int as part of its intended use. Because this is not the case, I've decided to use exit().

void itob(int num, char str[], int base) { if (base < 2 || base > 36) { exit(1); } int remainder = num; int i = 0;   while (remainder > 0) { int value = remainder % base; char place; if (value > 9) { place = 'A' + value - 10; } else { place = '0' + value; } str[i++] = place; remainder /= base; } // Our string is in reverse strrev(str); str[i] = '\0'; }
Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s . In particular, itob(n,s,16) formats n as a hexadecimal integer in s.

Comments

  • Russell Dias

    Posted on Sunday, 5th September 2010 @ 5:55pm.

    C seems to be treating you well. Must have been a huge change. From being given virtually everything in PHP, to well... practically nothing in C =P

    I guess moving to a complied language seems logical enough. Now I just need to find the time to do so.

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »