Output Memory Address As Binary?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    int x = 5;
    
    cout << &x << endl; // output binary not hex...HOW??
    
    return 0;
}


please help
Last edited on
closed account (48T7M4Gy)
If you want to convert hex to binary using C++ you'l have to write a small program/function. Google it and you'll find there are heaps of possibilities.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <bitset>

int main()
{
    using namespace std;
    
    int x = 5;
    
    cout << bitset<8*sizeof(int*)>(reinterpret_cast<long>(&x));
}


EDIT: I'm actually not quite sure about the cast; perhaps unsigned long is more appropriate ?
Last edited on
troll warlord ...you... are.... a.... god.... thank you!!!

please let me know how you knew how to do that!! thank you so much!
Last edited on
closed account (48T7M4Gy)
Excellent!
Take a look at this reference: http://www.cplusplus.com/reference/bitset/bitset/

Although you should actually try to convert hex to binary (or any number system to binary interchangebly) using pure logic
Last edited on
thanks troll I already knew about bitset... I should have been more specific..How you casted a pointer to int and reinterpret cast ..

I would like to hear how you learned or knew to use those casts and stuff...
Last edited on
Messing around with this site really helped.

I also learned through this site:

http://en.cppreference.com/w/
EDIT: I'm actually not quite sure about the cast; perhaps unsigned long is more appropriate ?
Both are technically wrong and would fail on Windows machine with 64bit addressing.

If you want to be really portable, use uintptr_t: http://en.cppreference.com/w/cpp/types/integer
I see, thanks!
Topic archived. No new replies allowed.