I'm writing a program in C++ and I have a char string, "1240717949684", which I need to convert into the time_t type. It is apparently far too big for functions like atoi(), unless I'm doing something wrong. I wrote my own atoi() using time_t instead of int but it seems that the problem is that the processor can't multiply with a number that is bigger than 32 bits? It always gives me junk values.
Yes, the value is too large for 32-bit integers. Since your version of the library uses 32-bit integers, you won't be able to convert it to a time_t, but you can probably still convert it to a long long.
OK, I tried helios's solution first and it worked until I tried to convert the long long into a time_t. As soon as I did that I got the junk values. Any ideas?
I've heard of Boost, PanGalactic, but haven't looked into it yet. That looks refreshingly easy, so I may try that if I can't get this method going. I'm compiling for 64-bit but it would be nice if it could work on 32 bit as well.
Since your version of the library uses 32-bit integers, you won't be able to convert it to a time_t
You cannot store that value in a time_t. There's no solution other than to use a 64-bit version of the C library or use a different time library that can take bigger UNIX time integers.
I'm compiling for 64-bit but it would be nice if it could work on 32 bit as well.
atoi() does integer conversion, atol() does long conversion, atoll() does long long conversion
Doing this portably using the ato*() conversion routines requires some work. time_t bar = atol(foo) will work in most cases, but there are certainly instances where time_t is not 32-bit on 32-bit platforms.
1 2 3 4 5 6 7 8 9 10 11 12 13
time_t bar;
if (sizeof(time_t) == sizeof(int))
{
bar = atoi(foo);
}
elseif (sizeof(time_t) == sizeof(long))
{
bar = atol(foo);
}
elseif (sizeof(time_t) == sizeof(longlong))
{
bar = atoll(foo);
}
One thing to note is that long long is not yet part of the C++ standard is therefore is not yet fully portable. I prefer lexical_cast.
And, as helios says, you cannot convert the value you have to a time_t on a platform where time_t is 32-bits.