C base conversion from decimal to ternary

  • A+
Category:Languages

I'm converting an integer value to a ternary number (which is a String). I suspect there should be a better way to achieve this with less computational effort.

My algorithm directly implements the long division method to convert a number between decimal and any base.

char *get_ternary_str(int value) {   char buffer[3] = { "000" };   int dividend = value;    int i = 0;   do {     int remainder = dividend % 3;     dividend = dividend / 3;     buffer[i] = ((char)remainder + '0');     i++;   } while(dividend >= 1 && i < 3);    char temp = buffer[2];   buffer[2] = buffer[0];   buffer[0] = temp;    return buffer; } 

Even if in this example the ternary number is 3 digits long, my goal is to make it n-digit long. Suggestions on how to do this to n-digit ternary numbers are also welcome.


  • You should allocate your buffer dynamically using malloc.
  • You can initialize your char array with zeros using memset.
  • And lastly, you can calculate the char array length mathematically. Ceiling to Log [value] base 3 will give you the character size of your string. And please keep in mind to add an extra char to use null.

Because of you ask for suggestion, i'm not providing code. But, if you need further help, you can indicate on comment.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: