how extracts values from a char array?
HI I have following char array in C,
char array[1024] = "My Message: 0x7ffff6be9600"
i have to extract the value "0x7ffff6be9600" only from above char开发者_运维技巧 array.
how can i extract the value with the use scanf() type functions?
Thanks in advance.
Use the sscanf
function, precisely for that.
For example:
unsigned long l;
if (3 == sscanf(array, "%*s %*s %lx", &l)) //ignore the words before the number
{
// got something
}
Look ma, no scanf
...
printf("%.14s", strstr(array, " 0x") + 1);
or, still no scanf
#include <stdio.h>
#include <string.h>
int main(void) {
char array[] = "My Message: 0x7ffff6be9600----";
char result[100];
char *tmp;
tmp = strstr(array, " 0x");
if (tmp) {
strncpy(result, strstr(array, " 0x") + 1, 14);
result[14] = 0;
printf("result: %s\n", result);
} else {
printf("invalid input\n");
}
return 0;
}
Perhaps something like this would work for you :
char IsDigit(char val)
{
if((val>47 && val<58))
return 1;
else if(val>64 && val<70)
return 2;
else if(val>96 && val<103)
return 3;
return 0;
}
__int64 GetHexInt64(char* text,int maxlen)
{
int i=0;
char state=0;
char dig;
__int64 res = 0;
int digcnt = 0;
while(i<maxlen && text[i]!='\0')
{
switch(state)
{
case 0:
if(text[i]=='0')
state++;
else
state=0;
break;
case 1:
if(text[i]=='x' || text[i]=='X')
state++;
else
state=0;
break;
}
i++;
if(state==2)
break;
}
if(state!=2)
return (__int64)-1;
while(i<maxlen && text[i]!='\0' && digcnt<16)
{
dig = IsDigit(text[i]);
if(dig)
{
digcnt++;
switch(dig)
{
case 1:
res<<=4;
res|=(text[i]-48) & 0x0f;
break;
case 2:
res<<=4;
res|=(text[i]-55) & 0x0f;
break;
case 3:
res<<=4;
res|=(text[i]-87) & 0x0f;
break;
}
}
else
{
break;
}
i++;
}
return res;
}
Sorry about the __int64
but I am unsure what is the correct type for a 64-bit integer in your compiler.
Here's a simple example using sscanf()
, which is fairly close to scanf()
:
> cat 7512438.c
#include <stdio.h>
int main() {
char array[1024] = "My Message: 0x7ffff6be9600";
unsigned long hex = 0UL;
if (sscanf(array, "My Message: 0x%lx", &hex) == 1) {
printf("%lx\n", hex);
} else {
printf("Sorry, could not extract anything useful from %s\n", array);
}
return 0;
}
> make 7512438
cc -Wall -I /opt/local/include -L/opt/local/lib 7512438.c -o 7512438
> ./7512438
7ffff6be9600
精彩评论