Write a program in c++ to accept a number and convert this number into binary or hexa decimal or octal number according to the user choice using the concept of array.
converting a number into binary or hexadecimal or octal using arrays
Collapse
X
-
For a moment, forget about C++ and let me ask you if you know how to convert a decimal number to binary?
If you don't, then no amount of C++ help is going to do any good.
So, take a decimal number, say 456, and convert it to binary.
Post the steps you took. Then we can start on the C++ implementation of your steps. -
The binary for 456 is 111001000.
If you are using Windows you can use the Calculator set on Programmer view to do this so you can check your results.
OK. So the value of the binary columns is:
256 128 64 32 16 8 4 2 1
You need to determine whether there is a 1 or 0 in each column:
Calculate 456/256 to get 1
Now subtract 256 from 456 to get 200
Calculate 200/128 to get 1
Now subtract 128 from 200 to get 72
Caculate 72/64 to get 1
Now subtract 64 from 72 to get 8
Calculate 8/32 to get 0
Don't subtract 32 because 32 is bigger than 8
Calculate 8/16 to get 0
Don't subtract 16 because 16 is bigger than 8
Calculate 8/8 to get 1
Now subtract 8 from 8 to get 0
Calculate 0/4 to get 0
Don't subtract 4 because 4 is bigger than 0
Calculate 0/2 to get 0
Don't subtract 2 because 2 is bigger than 0
Calculate 0/1 to get 0
Don't subtract 1 because 1 is bigger than 0
You are done.
There are several ways to code this and at this point you should take a crack at doing the code. Do not worry if your code isn't perfect or efficient. Just make it work. Post again so I can see what you did.Comment
-
Please forgive the following precise, pedantic, and tiresome rant; but I think it will help to dispel some confusion. Your problem statement ought to be something more like this...
Write a program that does the following:- Accept a user-entered string that contains a nonnegative decimal number.
- Validate the string (print an error if it contains anything other than the digits 0-9 or it has a value greater than can be held in whichever integral type you choose to use).
- Convert the string into a number.
- Print the value of the number as a string of binary digits.
- Print the value of the number as a string of octal digits.
- Print the value of the number as a string of hexadecimal digits.
You convert from string to number and then from number to string; but the integral number itself doesn't change once you've got it. Other posters have gotten quite confused -- thinking that they need to alter the way C stores integral values.
C++ has automagical ways to do these string conversions. It sounds like your assignment requires you to deliberately avoid doing it the easy way for the output strings. Are you allowed to take the easy way for converting the input string into the number?Comment
Comment