show memory locations

Hi all,

I have a question. How can I show a memory location in hexadecimal notation? I want to show &p in hexadecimal notation in stead of decimal.

for example:

1
2
3
4
5
6
7
8
9
10
11
   int          inputP = 10,
                inputQ = 25,
                *p,             //pointer to int inputP.
                *q;             //pointer to int inputQ.

   p = &inputP;
   q = &inputQ;

   cout << *p << &p << endl;
   cout << *q << &q << endl;


Thanks!
Well, there are two ways. The easy, boring way and the fun, but somewhat more difficult way. The second way isn't exactly "hard," but it's harder.

Easy way: use setf: http://www.cplusplus.com/reference/iostream/ios_base/setf/

To print in hex, you just
1
2
std::cout.setf(ios::hex, ios::basefield);
std::cout << 0x0123456789ABCDEF;


Fun way: convert the decimal number into an std::string in hex and print the string:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <algorithm>

std::string itos(int i, int base)
{
    std::string str;
    unsigned int ui = i;
    
    /* If i is negative and base is 10; then we put the sign in str */
    if (i < 0 && base == 10) {
        str += '-';
        ui = -i;
    }
    
    /* Now convert ui into a the base base and store the result in str */
    do {
        int rem = ui % base;
        
        str += (rem < 10) ? rem + '0' : rem + 'a' - 10;
    } while (ui /= base);

    /* Reverse the string: */
    std::reverse(str.begin(), str.end());
    
    return str;
}
int main() {
    int n = 0,
        base = 0;

    std::cout << "Enter a number and the base to convert it into\n"
              << "Number: ";
    std::cin >> n;

    std::cout << "Base: ";
    std::cin >> base;
    
    std::cout << "Decimal "  << n << " is " << itos(n, base)
              << " in base " << base << std::endl;
    
    return 0;
}
Enter a number and the base to convert it into
Number: 15
Base: 2
Decimal 15 is 1111 in base 2


Can you guess what will happen if you try base 1?
Last edited on
Hi chrisname,

Sorry for my late reply. My question was not meant to calculate decimal numbers into hexadecimal, but anyway base 1 would be 111111111111111 :)

I used the setf method in stead.

Cheers,
pinoynl
No, base 1 can't exist. What happens in the do-while loop if you call itos(16, 1)?

Hint: infinite loop

Edit: also, have you not noticed the pattern of numeric bases? The largest digit for base 10 is 9, or 10 - 1. The largest digit for base 6 is 5, or 6 - 1. So the highest digit for base 1 would be 0, or 1 - 1. Another reason why base 1 can't exist: it only has 1 digit, 0.
Last edited on
I noticed..thanks for your help :)
No problem.
Topic archived. No new replies allowed.