printf a 64-bit number

R

Richard Cavell

GCC 3.3, XCode:


#include <iostream>
#include <stdint.h>

int main (int argc, char * const argv[])
{
uint64_t a=10123123123LL;
printf("%d\n", a);
std::cout << a;
std::cout << "\n";
return 0;
}

The printf statement gives me 2 (which is the upper 32 bits of a). The
cout gives me the correct result. Is this expected behaviour? Surely
64 bit integers are de rigeur now.

I'm generally trying to use C and not C++ for portability and speed.
 
V

void

Richard said:
GCC 3.3, XCode:


#include <iostream>
#include <stdint.h>

int main (int argc, char * const argv[])
{
uint64_t a=10123123123LL;
printf("%d\n", a);

printf("%lld\n", a);

Best
Darek
 
R

Rolf Magnus

Richard said:
GCC 3.3, XCode:


#include <iostream>
#include <stdint.h>

int main (int argc, char * const argv[])
{
uint64_t a=10123123123LL;
printf("%d\n", a);
std::cout << a;
std::cout << "\n";
return 0;
}

The printf statement gives me 2 (which is the upper 32 bits of a). The
cout gives me the correct result. Is this expected behaviour?

Yes. You specified %d to printf, which means that you promised to pass an
int. But since you didn't actually pass an int, the result will be wrong.
Surely 64 bit integers are de rigeur now.

I'm generally trying to use C and not C++ for portability and speed.

What makes you believe printf is more portable and faster than cout? Do you
have any evidence that proves this?
 
M

msalters

Richard said:
GCC 3.3, XCode:


#include <iostream>
#include <stdint.h>

int main (int argc, char * const argv[])
{
uint64_t a=10123123123LL;
printf("%d\n", a);
std::cout << a;
std::cout << "\n";
return 0;
}

The printf statement gives me 2 (which is the upper 32 bits of a). The
cout gives me the correct result. Is this expected behaviour? Surely
64 bit integers are de rigeur now.

I'm generally trying to use C and not C++ for portability and speed.

Well, uint64_t isn't really portable. But I guess this shows:
with C it's easy to be wrong everywhere. You're probably very fast
in producing the wrong answer, but C++ is even faster:
in main() { } also produces the wrong output. It's also smaller.
The moral: being right is more important than petty concerns.

HTH,
Michiel Salters
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top