Created
July 13, 2020 20:33
-
-
Save thecyborganizer/5d55e9a3c54f50d851c8f463a0c49075 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <math.h> | |
#define MAX_STR_LEN 20 | |
char strbuf[16]; | |
char str[] = "10000:12:34"; | |
int convertTimestampToSeconds(char* ts) { | |
char* p = ts; | |
while (*(p++) != '\0') { | |
if ((p - ts) > MAX_STR_LEN) { | |
return -1; | |
} | |
} | |
int radix = 0; | |
int total = 0; | |
while(p >= ts) { | |
while(*p != ':' && p >= ts) { | |
p--; | |
} | |
int val = atoi(p+1); | |
// handle atoi parse failure | |
if (val < 0) { | |
return -1; | |
} | |
//convert to seconds | |
val *= pow(60, radix); | |
total += val; | |
radix++; | |
*p = '\0'; | |
p--; | |
} | |
return total; | |
} | |
int main() | |
{ | |
strcpy(strbuf, str); | |
int val = convertTimestampToSeconds(strbuf); | |
printf("%d\n", val); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment