topmop75 topmop75 - 6 months ago 54
C++ Question

Really long integer string to int conversion

I am getting this value from Google Drive API as drive size.


How can i convert that string to an int/long/unsigned in c++ Builder.

  1. StrToInt() cant, it say invalid integer.

  2. atol() also fails, it returns garbled value

  3. atoll() ? I cant seems to use that function in c++ Builder

Also what numeric data type of C++ builder can hold the value 16106127360 ?



16106127360 is too large to fit in a 32bit (unsigned) int 1. That value requires a 64bit (unsigned) __int64 or (unsigned) long long instead.

There are quite a number of different ways you can convert such a string value to a 64bit integer variable:

  • There are StrToInt64(), StrToInt64Def(), and TryStrToInt64() functions for __int64 values in the SysUtils.hpp header:

    __int64 size = StrToInt64("16106127360");

    __int64 size = StrToInt64Def("16106127360", -1);

    __int64 size;
    if (TryStrToInt64("16106127360", size)) ...

    (in modern C++Builder versions, there are also corresponding UInt64 functions for unsigned __int64 values as well)

  • There are strtoll()/wcstoll() functions in the stdlib.h header:

    long long size = strtoll("16106127360");

    long long size = wcstoll("16106127360");
  • you can use the sscanf family of functions in the stdio.h header, using the %lld or %llu specifiers:

    long long size;
    sscanf("16106127360", "%lld", &size);

    unsigned long long size;
    sscanf("16106127360", "%llu", &size);

    long long size;
    swscanf(L"16106127360", L"%lld", &size);

    unsigned long long size;
    swscanf(L"16106127360", L"%llu", &size);
  • you can use std::istringstream or std::wistringstream in the sstream header:

    std::istringstream iis("16106127360");
    __int64 size; // or unsigned
    iis >> size;

    std::wistringstream iis(L"16106127360");
    __int64 size; // or unsigned
    iis >> size;

1: (if you are compiling your C++Builder project for iOS 9, long is 64bit, otherwise it is 32bit on every other supported platform)