Here’s something I encountered while going through some legacy C code.
year = (p_dt_tm[0]-'0')*1000 + (p_dt_tm[1]-'0')*100 + (p_dt_tm[2]-'0')*10 + p_dt_tm[3]-'0'; mon = (p_dt_tm[4]-'0')*10 + p_dt_tm[5]-'0'; day = (p_dt_tm[6]-'0')*10 + p_dt_tm[7]-'0'; hour = (p_dt_tm[8]-'0')*10 + p_dt_tm[9]-'0'; min = (p_dt_tm[10]-'0')*10 + p_dt_tm[11]-'0'; sec = (p_dt_tm[12]-'0')*10 + p_dt_tm[13]-'0';
Can you figure out and explain what it’s supposed to do?
For bonus points, give an example of what the variable p_dt_tm
can contain.
Observation:
If you can view the code in fixed width font, then you’ll also notice the extent some programmers go to align their code nicely. See how all the plus signs line up vertically? And when the indices go to 2 digits, the programmer deliberately removed some spaces to realign.
looks like a string conversion…
string p_dt_tm = “20081110101623”;
int year = (p_dt_tm[0]-‘0’)*1000 + (p_dt_tm[1]-‘0’)*100 +
(p_dt_tm[2]-‘0’)*10 + p_dt_tm[3]-‘0’;
int mon = (p_dt_tm[4]-‘0’)*10 + p_dt_tm[5]-‘0’;
int day = (p_dt_tm[6]-‘0’)*10 + p_dt_tm[7]-‘0’;
int hour = (p_dt_tm[8]-‘0’)*10 + p_dt_tm[9]-‘0’;
int min = (p_dt_tm[10]-‘0’)*10 + p_dt_tm[11]-‘0’;
int sec = (p_dt_tm[12]-‘0’)*10 + p_dt_tm[13]-‘0’;
// uk format..
Console.WriteLine(“{3,3}:{4,2}:{5,2} {2,2}/{1,2}/{0,4}”, new object[] {year, mon, day, hour, min, sec});
the input being a nice sortable date/time string of course…
Hi Philip, that’s right. I was thinking why the original programmer wanted to subtract a character zero, when I realised it’s for a shortcut calculation purpose.
I just think he could have added some comments (even if just a line) to say so.
And I didn’t know in UK, the time is displayed before the date. Is that a standard?
comments take up valuable disk space 😉
I would not says its standard, just common to use the time followed by date (check out news.bbc.co.uk) – really the time format should have be HH:MM.ss
Philip Fitzsimonss last blog post..XML Explorer