|
|
View previous topic :: View next topic |
Author |
Message |
erpgc82
Joined: 02 May 2020 Posts: 73
|
convert char to integer? |
Posted: Mon Aug 23, 2021 8:21 am |
|
|
Hi, how do I convert characters to integers?
I'm getting serial numbers like: 1, 2, 3, 4, 5, 6.
But an example the 2 and the 3, I get 50 and 51.
I tried
value = (int) receive[x];
value = toint (receive[x]; // this function no longer exists in CCS.
value = atoi(receive[x]); // this function no longer exists in CCS.
in another situation I did as below, and it worked:
if (x=='1') value = 1;
if (x=='2') value = 2;
and so on, it works, but it gets too long! _________________ Gradually you will go far with persistence, will and determination! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Aug 23, 2021 8:30 am |
|
|
toint is in the forum archives. Click the search link above and
type in toint and click the Search button. It's in the 2nd hit. |
|
|
erpgc82
Joined: 02 May 2020 Posts: 73
|
|
Posted: Mon Aug 23, 2021 10:16 am |
|
|
Ok thank you PCM Programmer!
It worked, my problem is solved, really easy.
but the question is, what does this definition do?
#define toint(c) ((int)((c)-'0'))
create a definition called toint ok
((c)-'0')
I didn't understand, I'm new to C CCS PIC, I've been programming for 1 year, I still consider myself an apprentice _________________ Gradually you will go far with persistence, will and determination! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Aug 23, 2021 10:33 am |
|
|
It removes the ASCII bias, leaving just the integer.
Look at an ASCII table on the internet. Notice that '0' (zero)
has the ASCII value of 0x30. '1' is 0x31, 2 is 0x32, etc,
If you subtract 0x30 from each of those, you get just the
integer value: 0, 1, 2, etc. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19590
|
|
Posted: Mon Aug 23, 2021 12:47 pm |
|
|
The key point, is whether you want to convert a whole sequence of
characters or just one.
The definition just converts the ASCII value for a numeric character to
it's numeric value.
If you study it, '0', gives the numeric ASCII value of the character 0.
If you run 'charmap' in Windows, and select the '0' character it tells you
this is ASCII 0x30. Also looking at the characters there the numeric
characters are sequential, so the maths in atoi, gives a numeric value of
zero for '0', and one for '1'' etc..
atoi, converts a whole string 'sequence' of characters into it's numeric
value.
So if you are receiving multiple characters, look at atoi. For the
single character use the definition... |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|