View previous topic :: View next topic |
Author |
Message |
jpts
Joined: 08 Mar 2017 Posts: 40
|
Converting Char into int |
Posted: Sun Mar 26, 2017 7:11 pm |
|
|
Why not working using ?
int k;
Char Mystring[20];
Mystring = "12345"
k = Mystring[0];
if (k == 1) Putc('O');
its work only if use 49(asc code) in this case if (k == 49) Putc('O'); |
|
|
drolleman
Joined: 03 Feb 2011 Posts: 116
|
|
Posted: Sun Mar 26, 2017 7:27 pm |
|
|
first are you using a 16/18 part because int is only 8 bits 0 - 255
int in pic24 or pic33 is 16 bit 0 - 65535.
to get the data would be k= atoi(Mystring), |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sun Mar 26, 2017 8:13 pm |
|
|
The string is ASCII characters. Therefore, do the comparison to an
ASCII character. This means compare it to '1' (and not to 1). They are
different. Do it like this:
Code: | if (k == '1') Putc('O'); |
|
|
|
jpts
Joined: 08 Mar 2017 Posts: 40
|
|
Posted: Mon Mar 27, 2017 7:09 pm |
|
|
worked using if (k == '1') Putc('O');
but how to convert char into int8. once atoi only work with string.
Take same example.
int k,y;
Char Mystring[20];
Mystring = "12345"
k = Mystring[0];
y = 2 + k; ????? for correct result should convert k into int ? toget y = 3 as result |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Mar 27, 2017 8:54 pm |
|
|
Use the toint() macro as shown in the example below.
The program will display the output as:
Code: | #include <18F46K22.h>
#fuses INTRC_IO, NOWDT, BROWNOUT, PUT, NOPBADEN
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
// This macro converts an ASCII hex digit from '0' to 'F'
// to an integer from 0x00 to 0x0F (0 to 15).
#define toint(c) ((c & 0x5F) > '9' ? c - '7' : c - '0')
//======================================
void main()
{
int8 k;
int8 Mystring[20] = "12345";
k = toint(Mystring[0]);
printf("%u ", k);
while(TRUE);
} |
|
|
|
|