How to add spaces to this output?

I want to separate this binary string every 4 characters..I am trying to get a better understanding of how variables are stored in memory and I am looking at their binary address for a pattern..I see a pattern for the last 4 bits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

#include <bitset>


int main()
{

    using namespace std;
    
    int  x[100];
    for(int i = 0; i < 100; i++)
    {
         x[i] = 1;
        cout << bitset<7*sizeof(double*)>(reinterpret_cast<long>(&x[i])) << endl;
    }


    cout << endl;
}
Last edited on
reinterpret_cast<long>(&x[i]) long is not large enough to reliably store a pointer. use uintptr_t instead.

bitset<7*sizeof(double*)> Why 7?

You can convert bitset to string and output it 4 characters at a time.
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
#include <iostream>
#include <bitset>
#include <cstdint>
#include <limits>

int main()
{
    const int N = 8 ;
    int x[N];

    for( int i = 0; i < N ; ++i )
    {
        x[i] = 1;
        const int* address = x + i ;
        const std::uintptr_t address_value = reinterpret_cast<std::uintptr_t>(address) ;

        const int NBITS = std::numeric_limits<std::uintptr_t>::digits ;
        const std::bitset<NBITS> bits(address_value) ;
        const std::string bitstr = bits.to_string() ;

        std::cout << std::dec << i << ". decimal: " << address_value
                  << std::showbase << std::oct << "   octal: " << address_value
                  << std::hex << "   hex: " << address_value
                  << "    bits: " ;
        const int NIBBLE_SZ = 4 ;
        for( int j = 0 ; j < NBITS/NIBBLE_SZ ; ++j ) std::cout << bitstr.substr( j*NIBBLE_SZ, NIBBLE_SZ ) << ' ' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/e43bed76267103e8
Topic archived. No new replies allowed.