万能进制转换代码C++
时间: 2023-07-10 19:36:26 浏览: 51
以下是 C++ 的进制转换代码示例:
```cpp
// 十进制转其他进制
string dec2base(int num, int base) {
string digits = "0123456789ABCDEF";
string res = "";
while (num > 0) {
res = digits[num % base] + res;
num /= base;
}
return res;
}
// 其他进制转十进制
int base2dec(string num, int base) {
int res = 0;
for (char c : num) {
res = res * base + (isdigit(c) ? c - '0' : c - 'A' + 10);
}
return res;
}
```
其中 `dec2base` 函数将一个十进制数转换成指定进制的字符串,`num` 为待转换的十进制数,`base` 为目标进制。例如,`dec2base(42, 2)` 将返回 `"101010"`。
`base2dec` 函数将一个指定进制的数转换为十进制数,`num` 为待转换的数的字符串表示,`base` 为原始进制。例如,`base2dec("101010", 2)` 将返回 `42`。
相关问题
十进制转换n进制 c++代码
当将十进制数转换为n进制数时,可以使用除法法则。以下是一个用C++编写的示例代码,可以将十进制数转换为任意进制数:
```cpp
#include <iostream>
#include <string>
std::string decimalToNBase(int decimal, int base) {
std::string result = "";
while (decimal > 0) {
int remainder = decimal % base;
if (remainder < 10) {
result = std::to_string(remainder) + result;
} else {
result = char(remainder - 10 + 'A') + result;
}
decimal /= base;
}
return result;
}
int main() {
int decimal;
int base;
std::cout << "Enter the decimal number: ";
std::cin >> decimal;
std::cout << "Enter the base: ";
std::cin >> base;
std::string nBaseNumber = decimalToNBase(decimal, base);
std::cout << "The equivalent number in base " << base << " is: " << nBaseNumber << std::endl;
return 0;
}
```
这个代码示例中,`decimalToNBase` 函数将十进制数 `decimal` 转换为 `base` 进制数,并返回一个字符串表示结果。函数使用除法法则来计算余数,并将余数转换为相应的字符(如果大于等于10,则使用字母表示)。最后,主函数通过用户输入获取十进制数和目标进制数,并打印转换结果。
请注意,此代码仅适用于将十进制数转换为小于等于16进制的其他进制数。如果需要转换为更高进制(例如32进制、64进制等),需要相应地修改代码。
c++实现任意进制转换代码、
好的,我可以为您提供任意进制转换的代码示例,您只需要提供需要转换的数和进制即可。
以下是C语言实现的任意进制转换代码:
```
#include <stdio.h>
void convert(int num, int base) {
char representation[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
char output[100];
int index = 0;
// Handle negative numbers
if (num < 0) {
printf("-");
num = -num;
}
// Convert to specified base
while (num > 0) {
int remainder = num % base;
output[index++] = representation[remainder];
num = num / base;
}
output[index] = '\0';
// Reverse output and display
for (int i = index - 1; i >= 0; i--)
printf("%c", output[i]);
}
int main() {
int num, base;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter the base: ");
scanf("%d", &base);
printf("Converted value: ");
convert(num, base);
printf("\n");
return 0;
}
```
在程序运行时,您需要输入两个整数:需要转换的数和进制。程序会将给定的数转换为指定的进制,并将结果输出到屏幕上。
希望这个代码示例能对您有所帮助!