15
How it works when you take a variable and do char-48
To transform in integer, as for example in this code I made, I used a date for example "22/05/1994" stored in a char vector and transformed in day, month and year all in integer value. The fact happens on line 5 in the expression num[j]=data[i]-48
. What happens in this operation to happen the conversion?
void transformarDataEmInt(char *data, int *dia, int *mes, int *ano){
int i,j=0;
int num[8];
for (i=0; i<10; i++) {
num[j]=data[i]-48;
if (i==2||i==5){
continue;
}
j++;
}
*dia = num[0]*10 + num[1];
*mes = num[2]*10 + num[3];
*ano = num[4]*1000 + num[5]*100 + num[6]*10 + num[7];
}
Very good explanation, thank you :D
– Nicolas Bontempo
Just to complement: C does not necessarily use the ASCII table. Thus
48
is not always'0'
, but'0'
is always'0'
. So you’d rather writedata[i] - '0'
.– Guilherme Bernal
Another point to note is that this works because whoever created the ASCII table had the sensitivity to leave the numeric characters in order. Otherwise the conversion would have to be at the base of the switch-case. Also, it is always good to arrive if the character is between '0' and '9' before making the conversion, just to be sure.
– C. E. Gesser
@C.E.Gesser In C the characters
'0'
to'9'
are always in order, regardless of whether ASCII is used or not. By standard (session 5.2.1/3): "In Both the source and Execution basic Character sets, the value of each Character after 0 in the above list of decimal digits Shall be one Greater than the value of the Previous."– Guilherme Bernal
That’s what I meant. I spoke of the ASCII table just for being the most basic and known.
– C. E. Gesser