By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,897 Members | 1,969 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,897 IT Pros & Developers. It's quick & easy.

Printing unsigned long long int's

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Edward Arthur" <ea*****@attbi.com> wrote in message
news:56**************************@posting.google.c om...
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::ostream& operator << (std::ostream&, 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
--
http://ivan.vecerina.com
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.