Need help with base conversion program?

Need help with base conversion program?
I'm little confused can any help or give us advice / step by step instructions to start. < Don't want any codes > i want try to produce the code but i no idea of tackling this .

Basically I need a program when the input is a number, a base for base 2 to base 16.

e.g = 110 b16 I need it to convert it hexadecimal conversion . etc.
and 110 b2 It should get a binary code.

Also using parameters not cin
Any help greatly appreciated.
Last edited on
So! when you pass stuff from command-line parameters, they come in your program as strings. This is what you have to do:

1- For easiness, convert those strings from null terminated strings to std::string (optional)
2a- Parse your strings. If you want to have a space between 110 and b16 (which I won't recommend, because you could simply pass it with no spaces and have b separate them), then you have to remove the "b" from the second string, and then use the function atoi() to convert to integers (or use stream operator >>).

2b- Parse your strings. If you DON'T want to have a space between them, just find that b, and save the numbers before in a string, and the numbers after in a string, and use atoi() to convert to integers (or use stream operator >>).

3- Now the conversion part comes. The idea that occures to me for that, is that you convert first, anyway, to binary, and then convert to hexadecimal if required.

To convert to binary, simply presume a number of digits that would be sufficient for that number (for 110, for example, 7 digits suffice). And then, subtract the powers of 2 recursively. So for that 110:

110 - 2^7 which is < 0 -> 0
110 - 2^6 = 46 which is >= 0 -> 1
46 - 2^5 = 14 which is >= 0 -> 1
14 - 2^4 which is < 0 -> 0
14 - 2^3 = 6 which is >= 0 -> 1
6 - 2^2 = 2 which is >= 0 -> 1
2 - 2^1 = 0 which is >=0 -> 1
All remaining digits are 0, which is 1 more digit.


Take the numbers on the right, and that's your binary :) : 01101110

Now for hexadecimal, take every 4 binary digits together, and convert them to hexadecimal. That should be easy :)

Cheers :)
Last edited on
Thanks a lot .
You're welcome! if your question is answered, please mark the topic as Solved.
One pretty standard approach makes use of the mod operator (%), which returns the remainder, and the fact the integer division throws the remainder away.

As far as the maths goes... (for the decimal value 123)

base 10

123 / 10 = 12 R 3
12 / 10 = 1 R 2
1 / 10 = 0 R 1

base 2

123 / 2 = 61 R 1
61 / 2 = 30 R 1
30 / 2 = 15 R 0
15 / 2 = 7 R 1
7 / 2 = 3 R 1
3 / 2 = 1 R 1
1 / 2 = 0 R 1

base 16

123 / 16 = 7 R 11
7 / 16 = 0 R 7

base 8

123 / 8 = 15 R 3
15 / 8 = 1 R 7
1 / 8 = 0 R 1

Etc.
Last edited on
Nice! I never knew this method myself. Pretty simple! Thanks!
Topic archived. No new replies allowed.