C++ - Getting size in bits of integer

fergaral picture fergaral · Mar 26, 2015 · Viewed 19k times · Source

I need to know whether an integer is 32 bits long or not (I want to know if it's exactly 32 bits long (8 hexadecimal characters). How could I achieve this in C++? Should I do this with the hexadecimal representation or with the unsigned int one?

My code is as follows:

mistream.open("myfile.txt");

if(mistream)
{
    for(int i=0; i<longArray; i++)
    {
        mistream >> hex >> datos[i];        
    }
}

mistream.close();

Where mistream is of type ifstream, and datos is an unsigned int array

Thank you

Answer

Useless picture Useless · Mar 26, 2015
std::numeric_limits<unsigned>::digits

is a static integer constant (or constexpr in C++11) giving the number of bits (since unsigned is stored in base 2, it gives binary digits).

You need to #include <limits> to get this, and you'll notice here that this gives the same value as Thomas' answer (while also being generalizable to other primitive types)


For reference (you changed your question after I answered), every integer of a given type (eg, unsigned) in a given program is exactly the same size.

What you're now asking is not the size of the integer in bits, because that never varies, but whether the top bit is set. You can test this trivially with

bool isTopBitSet(uint32_t v) {
  return v & 0x80000000u;
}

(replace the unsigned hex literal with something like T{1} << (std::numeric_limits<T>::digits-1) if you want to generalise to unsigned T other than uint32_t).