Reputation: 1248
I got some Ascii
values read from a file in C
using fgetc()
method.
It converts the numbers to their Ascii number like: the value 4 equals to 52 because 52 is it's Ascii code and so on with all the integers.
Now all the answers about this use pritf("%c",c)
to simply convert the 52 to 4 But I want to store the value 4 in an integer variable.
SomeCode:
int writeFileToArray(FILE* file, int* a, int length)
{
int i = 0;
char temp;
if (file == NULL)
{
return -1;
}
else
{
while (i < length)
{
*(a + i) = fgetc(file);
i++;
}
return 1;
}
}
Instead of getting 52,53,54 etc to the array i want to get 4,5,6 etc.
Thanks for the help.
Upvotes: 0
Views: 171
Reputation: 150108
That's fairly straightforward when dealing with ASCII encoding. Simply subtract 48 from the ASCII value to convert to the number represented.
int actualNumber = asciiValue - 48;
Depending on how reliable your input data is, it's usually wise to range check that the input is actually in the range '0' to '9'. You can get some pretty strange results down the road if you blindly apply that formula to ASCII values that don't represent numbers.
Upvotes: 4