Output Memory Address As Binary?

Sep 24, 2014 at 3:11am
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 Sep 24, 2014 at 3:14am
Sep 24, 2014 at 3:23am
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.
Sep 24, 2014 at 3:28am
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 Sep 24, 2014 at 8:08am
Sep 24, 2014 at 4:06am
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 Sep 24, 2014 at 4:06am
Sep 24, 2014 at 4:29am
closed account (48T7M4Gy)
Excellent!
Sep 24, 2014 at 5:10am
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 Sep 24, 2014 at 5:15am
Sep 24, 2014 at 5:58am
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 Sep 24, 2014 at 5:58am
Sep 24, 2014 at 7:59am
Messing around with this site really helped.

I also learned through this site:

http://en.cppreference.com/w/
Sep 24, 2014 at 8:20am
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
Sep 24, 2014 at 8:34am
I see, thanks!
Topic archived. No new replies allowed.