Printing unsigned long long int's

Discussion in 'C++' started by Edward Arthur, Nov 15, 2003.

  1. Hi,

    I'm trying to convert a string to an unsigned long long int.

    % /tmp/long
    str 0x20000
    base 16
    decimal 131072
    hex 20000
    str 0x1abcd8765
    base 10
    decimal ffffffff
    hex ffffffff

    But when the value is > 2^32 "cout" does not cooperate.

    % gcc -v
    Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs
    gcc version 2.96 20000731 (Red Hat Linux 7.1 2.96-98)


    % cat long.cc
    #include <iostream>
    #include <string.h>
    #include <stdlib.h>

    void print_str(char *str)
    {
    int base;
    long long int l;

    base = (strncasecmp(str, "0x", 2) == 0) ? 16 : 10;

    l = strtoul(str, NULL, base);

    cout << "str " << str << endl;
    cout << "base " << base << endl;
    cout << "decimal " << l << endl;
    cout << "hex " << hex << l << endl;
    }

    int main(void)
    {
    char str[80];

    strcpy(str, "0x20000");
    print_str(str);

    strcpy(str, "0x1abcd8765");
    print_str(str);

    return 1;
    }


    Its NOT homework!

    Thanks,
    /Ed
     
    Edward Arthur, Nov 15, 2003
    #1
    1. Advertisements

  2. Are you sure it is "cout" that is not cooperating?
    Note: if you pass zero as a base, strtoul will
    choose between decimal/octal/hex based on
    the usual C++ prefixes.
    But:
    strtoul returns a 'long', not a 'long long' unsigned.
    The C library has a strtoull (double-l) function since
    the 1999 version of the standard, which you can use
    instead if your platform supports it.
    These should be ok if your compiler and library
    support long long types. Note however that 'long long'
    is not currently standard in C++ (it was introduced
    in the 99 version of the C language).


    If cout really was the part that doesn't work, maybe the
    C++ library you use lacks the following operator overload:
    std::eek:stream& operator << (std::eek:stream&, unsigned long long);
    It would be easy enough to implement (a simplified version of) it,
    using sprintf to first do the conversion to a string...


    hth, Ivan
     
    Ivan Vecerina, Nov 15, 2003
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.