Преобразование, которое я написал от шестнадцатеричного до десятичного числа, не работает. Я не уверен, какая часть ошибочна. Должен ли я делать -7 или что-то еще.
int hex_to_dec(char hexnumber[])
{
int decimal = 0; //integer for the final decimal number
int bit; //integer representing numbers between 0-9 and letter a-f in hex number
//a char array containing the input hex number
int i=0,j=0;
//the integer i takes the length of the input array
i =strlen(hexnumber);
//while there is a next bit in the array
while(i!=0)
{
bit = hexnumber[j];
//if the bit is a digit do the following
if(('0' <= bit && bit <= '9'))
{
decimal = decimal * 16;
decimal = decimal + (bit - '0');
}
//if the bit is a letter do the following
if(('a' <= bit && bit <= 'z'))
{
decimal = decimal * 16;
decimal = decimal + (bit - '7');
}
i--;
j++;
}
if(('a' <= bit && bit <= 'z'))
{
decimal = decimal * 16;
decimal = decimal + (bit - '7');
}
cout<<decimal;
return decimal;
}
Выше мой код для этого.
Вместо
decimal = decimal + (bit - '7');
Пытаться:
decimal = decimal + (bit - 'a' + 10);
Это связано с тем, что бит 'a'
в base 16
означает десятичное значение 10
в base 10
.
Кроме того, вы должны удалить этот дополнительный оператор вне цикла while.
if(('a' <= bit && bit <= 'z'))
{
decimal = decimal * 16;
decimal = decimal + (bit - '7');
}
Чтобы разместить заглавные буквы, просто добавьте другое условие if в ваш цикл while.
if(('A' <= bit && bit <= 'Z'))
{
decimal = decimal * 16;
decimal = decimal + (bit - 'A' + 10);
}
int hex2dec(char hexnumber[])
{
// get rid of ancient C code (should take a string in the first place most likely)
string hex = hexnumber;
// use c++ to do the work for us
return stoi(hex, nullptr, 16);
}
isdigit
иisalpha
.