Reputation: 508
My problem is casting char * string to byte, for example it is a prototype of my function.
bool parseTemp(char *str, float *x, float *y, float *z);
I should parse char variable and and get the values.
char *str="1427709952";
The hex value of this integer is 0x55192000. So 0x55 is a byte,it is 85 in decimal system. 0x19 is a byte, the value is 25 in decimal system. 0x20 is a byte, it is 32 in decimal system. So we have three values 90, 25, 32. I have really no idea, how to do it ?
Upvotes: 0
Views: 5425
Reputation: 508
And here is my teacher's solution. The input text is : temp 1427709952 ; He looks for temp at first, if it exists then he gets the number.
bool parseTemp(char *str, float *motor, float *indoor, float *outdoor)
{
char *ptr;
char *nptr;
char tmp[100];
int temp;
bool ret=false;
nptr=strdup(str);
ptr=strtok(nptr, ";");
while(ptr !=NULL){
if(strstr(ptr,"temp")!=NULL){
ret=true;
break;
}
ptr=strtok(NULL, ";");
}
free(nptr);
sscanf(ptr,"%s %d",tmp,&temp);
*motor=(float)((temp&0xff000000)>>24);
*indoor=(float)((temp&0x00ff0000)>>16);
*outdoor=(float)((temp&0x0000ff00)>>8);
return ret;
}
Upvotes: 0
Reputation: 508
I edited Anto's code and got my own solution with float variables.
bool parseTemp(char *str,float *x,float *y,float *z)
{
int number;
sscanf(str,"%d",&number);
int *m=(int *)x;
int *i=(int *)y;
int *o=(int *)z;
*m=(number & 0XFF000000) >> 24;
*i=(number & 0x00FF0000) >> 16;
*o=(number & 0x0000FF00) >> 8;
*x=(float)(*m);
*y=(float)(*i);
*z=(float)(*o);
if(isdigit(*m)&&isdigit(*i)&&isdigit(*o))
return true;
else
return false;
}
Upvotes: 0
Reputation: 11258
I assumed that you want to retrieve bytes out of function. Possible solution using bit manipulation:
#include <stdio.h>
#include <stdbool.h>
bool parseTemp(char *str, int *x, int *y, int *z);
int main()
{
char *str="1427709952";
int x, y, z;
parseTemp(str, &x, &y, &z);
printf("parsed numbers: %d, %d, %d\n", x, y, z);
return 0;
}
bool parseTemp(char *str, int *x, int *y, int *z) {
int number;
sscanf(str, "%d", &number);
*x = (number & 0xFF000000) >> 24;
*y = (number & 0x00FF0000) >> 16;
*z = (number & 0x0000FF00) >> 8;
return true;
}
I changed float
s to int
s. Output should be 85, 25, 32
.
Upvotes: 1
Reputation: 12625
Google scanf() man page. You can convert hex input using that and hex output with sprintf(). Also check into atoi() stroll() and related functions.
Upvotes: 0