Discussion:
ascii to int conversion
(too old to reply)
Me
2011-09-29 18:19:54 UTC
Permalink
I have a char array containing ascii "ff01a1c0"
How do I convert it to separate int's of 255 01 161 192 ??
atoi() doesnt appear to work with ascii letters only numbers.
Thanks.
Geoff
2011-09-30 03:35:07 UTC
Permalink
Post by Me
I have a char array containing ascii "ff01a1c0"
How do I convert it to separate int's of 255 01 161 192 ??
atoi() doesnt appear to work with ascii letters only numbers.
Thanks.
Not exactly an MFC question.
You have to write a function to do it.

Think: strlen, strncpy and strtoul.
David Webber
2011-10-01 13:56:25 UTC
Permalink
"Me" wrote in message news:14mmyb4pnwhfs.1kdwxmcukehgf$***@40tude.net...

I have a char array containing ascii "ff01a1c0"
How do I convert it to separate int's of 255 01 161 192 ??
atoi() doesnt appear to work with ascii letters only numbers.
Thanks.


Using sscanf with a format string of "%2x%2x%2x%2x" ?

Can't remember if that would be expected to work. If not, then splitting it
into substrings and reading a number form each would certainly work.

Dave

-- David Webber
Mozart Music Software
http://www.mozart.co.uk
For discussion and support see
http://www.mozart.co.uk/mozartists/mailinglist.htm
Geoff
2011-10-01 22:42:22 UTC
Permalink
How about:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char str[] = "ff01a1c0";

int main(void)
{
unsigned long u;
unsigned i;
char s[] = " ";

for (i = 0; i < strlen(str); i += 2)
{
memmove(s, &str[i], 2);
u = strtoul(s, NULL, 16);
printf("%lu ", u);
}
puts("\n");
return 0;
}
Nobody
2011-10-02 00:27:20 UTC
Permalink
Post by Me
I have a char array containing ascii "ff01a1c0"
How do I convert it to separate int's of 255 01 161 192 ??
atoi() doesnt appear to work with ascii letters only numbers.
Besides what others suggested, this sounds like an IP address. You first
have to convert it to u_long, then call inet_ntoa() to convert it to a
string containing the IP.

I think calling inet_addr() with your hex input string prefixed with "0x"
would convert it to u_long.

Loading...