While I was writing code on a 64 bit machine for a c++ program,I noticed that printing the address of a variable (for example) returns just 12 hexadecimal characters, instead of 16. Here's an example code:
int a = 3 ;
cout sizeof(&a) << " bytes" << endl ;
cout << &a << endl ;
The output is:
8 bytes
0x7fff007bcce0
Obviously, the address of a variable is 8 byte (64 bit system). But when I print it, I get only 12 hexadecimal digits instead of 16.
Why this? I think that is due to the fact that the 4 "lost" digits
were leading zeroes, that were not printed. But this is only my
thought, and I wish to have a definitive and technically correct
answer.
How could I print the entire address? Is there a built-in solution,
or should I manually use "sizeof" in order to get the real lenght and
then add to the address the right number of zeroes?
Forgive me, I googled for a day for an answer to my stupid question, but I wasn't able to find an answer. I'm just a newbie.
(On stackoverflow I did not find any question/answer about what I needed to know, but maybe I'm wrong.)
Someone asks a pretty similar question here: c++ pointer on 64 bit machine
Hope this helps :)
To print the full 64bit address with leading zeros you can use:
std::cout
<< "0x"
<< std::hex
<< std::noshowbase
<< std::setw(16)
<< std::setfill('0')
<< n
<< std::endl ;
Got it from: How can I pad an int with leading zeros when using cout << operator?
I am currently writing a book on C++ and windows 32-bit programming for peeps such as you, but unfortunately I am not yet done with it :(
The following code demonstrates how you would display a 64-bit unsigned number using cout method:
// Define a 64-bit number. You may need to include <stdint.h> header file depending on your C++ compiler.
uint64_t UI64 = 281474976709632ULL; // Must include ULL suffix and this is C99 C++ compiler specific.
// unsigned __int64 UI64 = 281474976709632ULL; // Must include ULL suffix and this is Microsoft C++ compiler specific.
// Set decimal output.
cout << dec;
// Display message to user.
cout << "64-bit unsigned integer value in decimal is: " << UI64 << endl;
cout << "\n64-bit unsigned integer value in hexadecimal is: ";
// Set the uppercase flag to display hex value in capital letters.
cout << uppercase;
// Set hexadecimal output.
cout << hex;
// Set the width output to be 16 digits.
cout.width(16);
// Set the fill output to be zeros.
cout.fill('0');
// Set right justification for output.
right(cout);
// Display the 64-bit number.
cout << UI64 << endl;
You may need to (type) cast the address into a 64-bit unsigned value.
In this case, you can do the following:
// (type) cast pointer adddress into an unsigned 64-bit integer.
uint64_t UADD64 = (uint64_t)&UI64; // C99 C++ compiler specific.