dimanche 8 octobre 2017

How long long is represented in memory?

I am not an advanced C++ programmer. But I have been using C++ for a long time now. So, I love playing with it. Lately I was thinking about ways to maximize a variable programmatically. So I tried Bitwise Operators to fill a variable with 1's. Then there's signed and unsigned issue. My knowledge of memory representation is not very well. However, I ended up writing the following code which is working for both signed and unsigned short, int and long (although int and long are basically the same). Unfortunately, for long long, the program is failing.

So, what is going on behind the scenes for long long? How is it represented in memory? Besides, Is there any better way to do achieve the same thing in C++?

#include <bits/stdc++.h>
using namespace std;



template<typename T>
void Maximize(T &val, bool isSigned)
{
    int length = sizeof(T) * 8;
    cout << "\nlength = " << length << "\n";

    // clearing
    for(int i=0; i<length; i++)
    {
        val &= 0 << i;
    }

    if(isSigned)
    {
        length--;
    }

    val = 1 << 0;
    for(int i=1; i<length; i++)
    {
        val |= 1 << i;

        cout << "\ni = " << i << "\nval = " << val << "\n";
    }
}


int main()
{
    long long i;

    Maximize(i, true);

    cout << "\n\nsizeof(i) = " << sizeof(i) << " bytes" << "\n";
    cout << "i = " << i << "\n";

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire