Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(+D) |
(added C++ version) |
||
Line 63: | Line 63: | ||
Put_line("1a (base 16) is decimal" & Integer'image(To_Decimal("1a", 16))); |
Put_line("1a (base 16) is decimal" & Integer'image(To_Decimal("1a", 16))); |
||
end Number_Base_Conversion;</ada> |
end Number_Base_Conversion;</ada> |
||
=={{header|C++}}== |
|||
<cpp>#include <limits> |
|||
#include <string> |
|||
#include <cassert> |
|||
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; |
|||
std::string to_base(unsigned long num, int base) |
|||
{ |
|||
int const max_size = std::numeric_limits<char>::digits * sizeof(unsigned long); |
|||
char s[max_size + 1]; |
|||
char* pos = s + max_size; |
|||
*pos = '\0'; |
|||
if (num == 0) |
|||
{ |
|||
*--pos = '0'; |
|||
} |
|||
else |
|||
{ |
|||
while (num > 0) |
|||
{ |
|||
*--pos = digits[num % base]; |
|||
num /= base; |
|||
} |
|||
} |
|||
return pos; |
|||
} |
|||
unsigned long from_base(std::string const& num_str, int base) |
|||
{ |
|||
unsigned long result = 0; |
|||
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos) |
|||
result = result * base + digits.find(num_str[pos]); |
|||
return result; |
|||
}</cpp> |
|||
=={{header|D}}== |
=={{header|D}}== |