C++ question

quirky

Senior member
Jun 25, 2002
398
0
0
I dont understand why

//
char array[10] = "012345678";

cout << hex << int(array[0]) << dec << " " << int(array[0]);

//


prints "30 48"'

can someome please explain this to me??
 

Turkey

Senior member
Jan 10, 2000
839
0
0
The ascii code for "0" is 48dec or 0x30, so int(array[0]) = int("0") = int(0x30) = 0x30.
 

quirky

Senior member
Jun 25, 2002
398
0
0
hmm, okay but using int("0") does not produce the same outpout as int(array[0]). how come? isnt int(array[0]) identical to 0?
 

PowerMacG5

Diamond Member
Apr 14, 2002
7,701
0
0
When you declare a character array, and then convert whatever is inside the array to an integer, it uses the ASCII code. For integer, the ASCII code is 48 above what it actually is. So in the case of single digit integers, just subtract 48 from what you receive when you state int(array[0]) and you should receive the correct answer.

ex:
//
char array[10] = "012345678";

cout << hex << int(array[0]) - 48 << dec << " " << int(array[0]) - 48);

//

hope this helps.
 

quirky

Senior member
Jun 25, 2002
398
0
0
Originally posted by: KraziKid
When you declare a character array, and then convert whatever is inside the array to an integer, it uses the ASCII code. For integer, the ASCII code is 48 above what it actually is. So in the case of single digit integers, just subtract 48 from what you receive when you state int(array[0]) and you should receive the correct answer.

ex:
//
char array[10] = "012345678";

cout << hex << int(array[0]) - 48 << dec << " " << int(array[0]) - 48);

//

hope this helps.

yes, i understand that. and actually, its cout<<hex<<int(array[0])-30 << dec << " " << int(array[0] - 48); which would output 0 0

but what exactly does int(array[0]) mean because cout<< hex<< int(0) does not produce the same output as cout<<hex<<int(array[0])
 

PCHPlayer

Golden Member
Oct 9, 2001
1,053
0
0
First of all you are doing something that is legal, but not very smart. Try cout << int('0'); That will give you what you expect. When you convert "0" to an int, you are converting the address of the string to an int. Since "any string" is actually of type const char *. What are you getting for an output of int("0"). I bet it is a large number.
 

PrincessGuard

Golden Member
Feb 5, 2001
1,435
0
0
0 is an integer. int(0) is 0

'0' is a character. int('0') is 0x30.

"0" is a null-terminated string. int("0") gives you the address of the string "0".