Base conversion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Base conversion

Is there a function in C or C++ Standard library that converts bases? like converting decimal to octal or hex to decimal?

29th Jan 2020, 10:12 PM
Zohal
Zohal - avatar
1 Answer
+ 3
Yes, you can use unsigned int: unsigned int n = 16; // decimal input unsigned int m = 0xFF; // hexadecimal input std::cout << std::dec << "Decimal: " << n << ", " << m << std::endl; std::cout << std::hex << "Hexadecimal: 0x" << n << ", 0x" << m << std::endl; Octal is also supported, though for other bases you had best write your own algorithm - it's essentially a three-liner in C++: std::string to_base(unsigned int n, unsigned int base) { static const char alphabet[] = "0123456789ABCDEFGHI"; std::string result; while(n) { result += alphabet[n % base]; n /= base; } return std::string(result.rbegin(), result.rend()); } The inverse unsigned int from_base(std::string, unsigned int base) function is similar (Not mine, StackOverflow)
29th Jan 2020, 10:17 PM
Gevork Bagratyan