Question:
CONVERSIONS OF Binary, Decimal, Octal, Hexadecimal C++?
mAie
2011-09-30 06:31:45 UTC
please help me. i need the following codes:

1. Binary to Decimal
2. Binary to Octal
3. Binary to Hexadecimal
4. Octal to Decimal
5. Octal to Hexadecimal
6. Octal to Binary
7. Hexadecimal to Decimal
8. Hexadecimal to Binary
9. Hexadecimal to Octal

-----
Note: This program will allow the user to input certain numbers that must be converted.
Kindly please help., even if you could give me at least one or more code., i would really really appreciate it!!!! :))
Three answers:
?
2011-09-30 07:13:07 UTC
For octal, use std::oct

http://www.cplusplus.com/reference/iostream/manipulators/oct/



For hex, use std::hex

http://www.cplusplus.com/reference/iostream/manipulators/hex/



For decimal, use std::dec (it's the default, but oct and hex are sticky)

http://www.cplusplus.com/reference/iostream/manipulators/dec/



For binary, use bitset:

http://www.cplusplus.com/reference/stl/bitset/



For example, here's your

7. Hexadecimal to Decimal

8. Hexadecimal to Binary

9. Hexadecimal to Octal



#include

#include

#include

#include

std::string to_bin(int n)

{

     std::string bits = std::bitset(n).to_string();

     return n == 0 ? "0" : bits.substr(bits.find('1'));

}

int main()

{

     std::cout << "Enter a hexadecimal number: ";

     int n;

     std::cin >> std::hex >> n;

     std::cout << "Hex: " << std::hex << n << '\n'

                   << "Dec: " << std::dec << n << '\n'

                   << "Oct: " << std::oct << n << '\n'

                   << "Bin: " << to_bin(n) << '\n';

}



test: https://ideone.com/TQSko



(the last one could be simply

     << "Bin: " << std::bitset<32>(n) << '\n';

if you don't mind the leading zeroes and know the number of bits you wish to display)
2011-09-30 16:45:26 UTC
the problem with u is that u dnt give a good response to ur answerers. i gave answers to many of ur questions...but u didnt react to them. u dont even choose best answer for ur questions.

thats why i m not going to help u anymore.
2011-09-30 14:05:12 UTC
ask this question on stackoverflow.com


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...