如何使十六进制到十进制转换器不使用它在c++中的函数?



所以我需要做一个十六进制到十进制的转换器,用户决定他想要输入多少数字(例如,如果他输入3个程序,让他写3个十六进制数字转换为十进制),但正如我之前所说,我必须手动进行转换,我只能使用库iostream, cstring和cmath。我不能使用字符串(当用户输入十六进制数字时,它们不能是字符串(真的不知道如何解释这一点),所以例如十六进制数字将存储在char十六进制中,而不是字符串十六进制),如果你能帮助我,我会非常感激,我希望我描述的问题足够好!

这是我的尝试(我是新的编程,所以它是相当糟糕)

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int main()
{
int broj;
do
{
cout << "Unesite broj brojeva: ";
cin >> broj;
}
while (broj < 1);
char *hex = new char [broj];
for (int i = 0; i < broj; i++)
{
cout << "Unesite " << i+1 << ". broj: ";
cin >> hex[i];
}
for (int i = 0; i < broj; i++)
{
char idk[10000];
idk[10000] = hex[i];
int duljina = strlen(idk);
int pom = 0;
int halp = duljina;
for (int j = 0; i < duljina; i++)
{
if (idk[j] == 'A' || idk[j] == 'a') idk[j] = 10;
if (idk[j] == 'B' || idk[j] == 'b') idk[j] = 11;
if (idk[j] == 'C' || idk[j] == 'c') idk[j] = 12;
if (idk[j] == 'D' || idk[j] == 'd') idk[j] = 13;
if (idk[j] == 'E' || idk[j] == 'e') idk[j] = 14;
if (idk[j] == 'F' || idk[j] == 'f') idk[j] = 15;
pom += idk[j]*(pow(16, halp));
halp--;
}
cout << pom << endl;
}
return 0;
}

它不工作

总是试着把你的关注点分开。我不会处理输入/输出,我假设你能处理它。那么,让我们实现一个函数,将一定长度的字符数组转换为十进制:

int getDigit(char input) {
switch (input) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'a':
case 'A': return 10;
case 'b':
case 'B': return 11;
case 'c':
case 'C': return 12;
case 'd':
case 'D': return 13;
case 'e':
case 'E': return 14;
case 'f':
case 'F': return 15;
}
return 0;
}
long hex2Decimal(char input[], int length) {
long output = 0;
long digit = 1;
int index = 0;
for (index = length - 1; index >= 0; index--) {
output += getDigit(input[index]) * digit;
digit *= 16;
}
return output;
}

注意,此代码支持的位数是有限的。为简单起见,我将不讨论对更高级的情况的支持。

由于这显然是家庭作业,我不想只是为您发布代码。但我研究了一下,发现了几个问题。我建议按以下顺序服用:

你有一个循环来读取所有的字符串。好的,但是尽管字符串数组是动态分配的,但是每个字符串都有而不是被分配。这有出错的风险。解决办法是什么?一个简单的方法是:摆脱那个循环。在最后一个for循环中,读入要处理的字符串。处理它并显示它的输出。然后做下一个。

如果你真的想把它们全部读入,然后处理它们,只需要让每个字符串不被动态分配。可以这样做:

using str = char [256];
str* hexes = new str[broj];

使用idk数组使事情变得复杂。如何这个算法打印一个十六进制字符串?

for each character in the hex string counting BACKWARDS from the last character
pom *= 16; //multiply the number you've got so far by 16 -- like moving left a digit
figure out what the new digit means
add that digit to pom

这消除了对idk数组的需要,因此您不必担心在其中读取太多