Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print addresses (Hex values) in upper case in c++

Tags:

c++

I'm trying to print the address(reference) of a variable in hex and that too in upper case. But I see that I'm able to print the hex equivalent of 77 in upper case, but not the address(reference) of a variable. Can somebody help me please?

The following is the program I have the difficulty with.

#include <iostream>
#include <string>

using namespace std;


void print_nb_of_items(const int nb_of_apple, const int& nb_of_pens)
{
    cout << "Number of apples = " << nb_of_apple << endl;
    cout << "Number of pens = " << nb_of_pens << " Address = " << uppercase << hex << &nb_of_pens << endl;
    cout << "Hex output in uppercase = " << uppercase << hex << 77 << endl;
}

/* The main function */

int main(int argc, char * argv[])
{
    int nb_apple = 24;
    int nb_pens = 65;
    print_nb_of_items(nb_apple, nb_pens);

    return 0;
}

The output for the program I got is:

Number of apples = 24
Number of pens = 65 Address = 0xbffbd438
Hex output in uppercase = 4D

I want the address to be printed as: 0xBFFBD438. How do I do that?

like image 596
Venkata Pavan Avatar asked Jan 09 '23 19:01

Venkata Pavan


2 Answers

"I want the address to be printed as: 0xBFFBD438. How do I do that?"

Well, @MatsPetterson hit the nail on the head in his comment, casting the address value to a uintptr_t

cout << "Number of pens = " << nb_of_pens 
     << " Address = 0x" << uppercase << hex 
     << uintptr_t(&nb_of_pens) << endl;
     // ^^^^^^^^^^           ^

just makes it work fine (see fully working sample here please).


To explain in more depth:
The implementation of

 std::ostream operator<<(ostream& os, void* ptr);

isn't further specified by the standard, and may simply not be affected by/considering the std::uppercase I/O manipulator. Conversion of the pointer value to a plain number, will take the std::uppercase and std::hex I/O manipulators into effect.

like image 63
πάντα ῥεῖ Avatar answered Feb 02 '23 17:02

πάντα ῥεῖ


Like printf("%p", &obj), the stream output format of a pointer is entirely unspecified. By convention we get a hexadecimal value and, on some systems, that abides by std::uppercase (and friends). But you cannot rely on that. Those I/O manipulators are there for numbers, not pointers.

You can actually transform your pointer into a number to guarantee the behaviour you want:

cout << "Number of pens = " << nb_of_pens
     << " Address = " << uppercase << hex << uintptr_t(&nb_of_pens)
     << endl;
like image 40
Lightness Races in Orbit Avatar answered Feb 02 '23 17:02

Lightness Races in Orbit