Reputation: 11
How to split a string into 2 bytes by 2 bytes.I want to get time information as integer value from string.
char buffer[10]= "101507";
int hour = < 10
int min = < 15
int sec = < 07
Upvotes: 0
Views: 757
Reputation: 44250
#include <stdio.h>
#define BARF(m) fprintf(stderr,"Barf: %s\n", m)
int main(int argc, char **argv)
{
unsigned val;
char *str = argv[1] ? argv[1] :"101507";
int hh,mm,ss;
for(val=0; *str; str++) {
if (*str < '0' || *str > '9') {BARF(str); continue;}
val *= 10; val += (*str - '0');
}
ss = val % 100; val /= 100;
mm = val % 100; val /= 100;
hh = val % 100;
printf("%02d:%02d:%02d\n", hh, mm, ss);
return 0;
}
Upvotes: 0
Reputation: 44329
You can do the calculation directly on the individual chars. Just subtract '0'
to get the numerical value. Like
char buffer[10]= "101507";
int hour = 10 * (buffer[0] - '0') + (buffer[1] - '0');
int min = 10 * (buffer[2] - '0') + (buffer[3] - '0');
int sec = 10 * (buffer[4] - '0') + (buffer[5] - '0');
or write a simple function that takes two chars as arguments
int chars_to_int(char msd, char lsd)
{
return 10 * (msd - '0') + (lsd - '0');
}
char buffer[10]= "101507";
int hour = chars_to_int(buffer[0], buffer[1]);
int min = chars_to_int(buffer[2], buffer[3]);
int sec = chars_to_int(buffer[4], buffer[5]);
or write a simple function that takes a char pointer as argument
int chars_to_int(char* p)
{
return 10 * (p[0] - '0') + (p[1] - '0');
}
char buffer[10]= "101507";
int hour = chars_to_int(&buffer[0]);
int min = chars_to_int(&buffer[2]);
int sec = chars_to_int(&buffer[4]);
Upvotes: 1
Reputation: 51864
You can use the sscanf()
function, with specified field widths of 2
for each of your three variables:
#include <stdio.h>
int main()
{
char buffer[10] = "101507";
int hour, min, sec;
if (sscanf(buffer, "%2d%2d%2d", &hour, &min, &sec) != 3) {
printf("Error reading data\n");
}
else {
printf("Hour = %02d, Min = %02d, Sec = %02d\n", hour, min, sec);
}
return 0;
}
Upvotes: 3