Printing unsigned long long int's

E

Edward Arthur

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
 
I

Ivan Vecerina

Edward Arthur said:
I'm trying to convert a string to an unsigned long long int. ....
But when the value is > 2^32 "cout" does not cooperate.

Are you sure it is "cout" that is not cooperating?
#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);
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.
cout << "str " << str << endl;
cout << "base " << base << endl;
cout << "decimal " << l << endl;
cout << "hex " << hex << l << endl;
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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top