Hexadecimal

I need some help with this program. If you can say me what exactly means those notation: 'a', 'f', and what happens in every major sequence of every function. This program convert a string to int and hexadecimal numbers to int.
Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include<iostream>
#include<cstring>
using namespace std;

int str2int(const char* c)
{
	int x=strlen(c),nr=0,pow=1;
	for (int i=x-1; i>=0; i--,pow*=10)
		nr=nr+(c[i]-'0')*pow;
	return nr;
}
int str2int2(const char* c)
{
	int x=strlen(c),nr=0,pow=1;
	for (int i=x-1; i>=0; i--,pow*=16)
		if (c[i]>='a' && c[i]<='f')
			nr=nr+(c[i]-'a'+10)*pow;
		else
			if (c[i]>='A' && c[i]<='F')
				nr=nr+(c[i]-'A'+10)*pow;
			else
				nr=nr+(c[i]-'0')*pow;
	return nr;
}
int main()
{
	char c[]="1234";
	char c2[]="ffff";
	cout<<str2int(c)<<endl;
	cout<<str2int2(c2);
	return 0;
}
Well as i recall from my IT class, 'A' is base 10 and 'F' is base 15, it goes like this
1
2
3
4
5
6
7
8
9
A : 10
B : 11
C : 12
D : 13
E : 14
F : 15
Last edited on
yes.this I know
but what exactly means this sequence for example: c[i]>='a' && c[i]<='f'
with what is compared c[i]?
This c[i]>='a' && c[i]<='f'
is a combination of two conditions: c[i] >= 'a' and c[i] <= 'f'
The && (logical and) operator means that the complete condition is true only if both of the conditions are true, that is, it is testing that c[i] is somewhere in the range 'a' to 'f' inclusive.
What means " '0' "?
'A' is the letter A, similarly '0' is the character representing the digit 0, as distinct from the number zero.
What values have 'a', '0' and 'f'. this is what i don't understand
http://www.asciitable.com/
'a' is decimal 97
'A' is decimal 65
'0' is decimal 48
etc.
ok.I understood.
now I want to know what value will return this nr=nr+(c[i]-'0')*pow; what does exactly this sequence?
Last edited on
Look at each term in this expression: nr + (c[i]-'0') * pow
the part in parentheses is evaluated first, then the multiplication by pow and finally the addition. Lastly, the end result is assigned to nr.
Last edited on
and, for example, for nr=4, pow=10 and c[i]=3 what value has this?
Surely you can work this out for yourself? Or at least have a go. If all else fails, you could add a cout << statement to display the result.
the last question
if 'a'=10 in hexadecimal why is necessary to write nr=nr+(c[i]-'a'+10)*pow;
and not more simply nr=nr+c[i]*pow?
Last edited on
Because 'a' == 97.
97 - 97 == 0
0 + 10 = 10

say you have b
'b' == 98
98 - 98 = 1
1 + 10 = 11

ect...from a - f
i don't understand.98-98=1?
if 'a'=10 in hexadecimal
But it doesn't. That's an erroneous starting point.
'a' = 97 in decimal, or 61 in hexadecimal (6* 16 + 1*1 = 97).

The character 'a' or 'A' is used to represent the hexadecimal digit which has a value of 10(decimal).
thanks.now i understand all
thank you very much
I meant 98 - 97 == 1 it was a typo.
Topic archived. No new replies allowed.