Converting denary to other bases

This is a discussion on Converting denary to other bases within the C++ Programming forums, part of the General Programming Boards category; Could anyone supply me with an algoritm to convert decimal numbers to other bases, 2 to 10 and above 10 ...

1. Converting denary to other bases

Could anyone supply me with an algoritm to convert decimal numbers to other bases, 2 to 10 and above 10 if possible. Many thanks.

2. x / base
x % base

That, and a for loop is pretty much all you need.

3. itoa() ...if your compiler supports it.

itoa(); // integer to ASCII (non-standard)

This is the easiest way, but it's non-standard. It's _itoa() in my Microsoft compiler.

Decimal, Hex, and Octal are built-in. You can use <bitset> for binary output, which is also standard.

Keep in-mind that all conversion takes place ONLY during input/output. Numbers are always stored in binary in the computer's memory. By default, everything is automatically converted to decimal for the user. This might seem confusing, but it means that you can enter a hex number and a decimal number and then add them together without worring about the base. Then, you can display the result in whatever base you want.

The attached example uses all of the above techniques as well as strtoul() to convert input.

4. Thank you both for your replies. I'm not using a compatiable compiler for your example Doug, but thanks anyway. Salem having a little trouble with your suggestion think it will require a step where we would * 10, got it working for 4, 2 and a couple of others but not quite perfect yet. I'm thinking that some kind of recursive function may be the best idea. Any thoughts?

5. Posting what you have so far perhaps

The algorithm doesn't care about what base you have, so if you've already done it for one base, the others should follow quite easily.

6. I've found this in a text book but am having trouble understanding it

den2base(x, y) = 0 if x <= 0
den2base(x, y) = den2base(x/y, y) mult 10) + (x mod y)

I've tried to replicate this in code but guess I'm going wrong somewhere.

7. Basic base formula

the basic formula is as follows

(value*base^position-1)+ (value*base^position-1)

lets say base is decimal the values are 0-9. for the number
100 if you plug in the formual goes like this

(1*10^2)+(0* 10^1)+ (0 *10^0)

if the base were binary and the number was 3 it would be like so

11=binary for 3

(1*2^1) +(1*2^0)

for hex (we use base 16 and the decimal values for abcdef)

A=hex for decimal 10

(10*16^0)

basically for bases above 10 you map letters(or symbols if you want) to represent the higher values

A=10 B=11 C=12 D=13 E=14 F=15 G=16 E=17 &=18 *=19