Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Getting size in bits of integer

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

like image 583
fergaral Avatar asked Mar 26 '15 17:03

fergaral


Video Answer


3 Answers

Try this:

#include <climits>

unsigned int bits_per_byte = CHAR_BIT;
unsigned int bits_per_integer = CHAR_BIT * sizeof(int);

The identifier CHAR_BIT represents the number of bits in a char.

The sizeof returns the number of char locations occupied by the integer.

Multiplying them gives us the number of bits for an integer.

like image 82
Thomas Matthews Avatar answered Oct 19 '22 06:10

Thomas Matthews


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).

like image 34
Useless Avatar answered Oct 19 '22 04:10

Useless


As already hinted in a comment by @chux, you can use a combination of the sizeof operator and the CHAR_BIT macro constant. The former tells you (at compile-time) the size (in multiples of sizeof(char) aka bytes) of its argument type. The latter is the number of bits to the byte (usually 8).

You can encapsulate this nicely into a function template.

#include <climits>   // CHAR_BIT
#include <cstddef>   // std::size_t
#include <iostream>  // std::cout, std::endl

template <typename T>
constexpr std::size_t
bit_size() noexcept
{
  return sizeof(T) * CHAR_BIT;
}

int
main()
{
  std::cout << bit_size<int>() << std::endl;
  std::cout << bit_size<long>() << std::endl;
}

On my implementation, it outputs 32 and 64.

Since the function is a constexpr, you can use it in static contexts, such as in static_assert<bit_size<int>() >= 32, "too small");.

like image 6
5gon12eder Avatar answered Oct 19 '22 04:10

5gon12eder