char* to time_t

Hello,

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.

Thanks,
crh
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.
Are you compiling the application 64-bit or 32-bit?

Check out the Boost Conversion Library, specifically lexical_cast.

If your time_t can hold that value, you can do:

1
2
3
4
5
6
7
8
9
char* bar = "1230717949684";
try
{
    time_t foo = boost::lexical_cast<time_t>(bar);
}
catch (boost::bad_lexical_cast& ex)
{
    // conversion failed
}


If you want to do what lexical_cast is doing behind the scenes, you can do:

1
2
3
4
std::string bar = "1230717949684";
std::istringstream ss(bar);
time_t foo;
ss >> foo;

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.
That's impossible, as well.
Last edited on
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);
}
else if (sizeof(time_t) == sizeof(long))
{
    bar = atol(foo);
}
else if (sizeof(time_t) == sizeof(long long))
{
    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.
Last edited on
Ok, thanks for the help guys, I'm going to download the boost libraries and do it that way.
Topic archived. No new replies allowed.