Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ limit of unsigned int through template

I'm using a template to convert integral types into a string representation of their binary values. I used the following:

template<typename T>
std::string ToBinary(const T& value)
{
    const std::bitset<std::numeric_limits<T>::digits + 1> bs(value);
    const std::string s(bs.to_string());

    return s;
}

It works for int but doesn't compile with unsigned int :

unsigned int buffer_u[10];
int buffer_i[10];
...
ToBinary(buffer_i[1]); //compile and works
ToBinary(buffer_u[1]); //doesn't compile -- ambiguous overload

Could you explain why?

EDIT:

Yes, I'm using VS2010

like image 415
Heisenbug Avatar asked Jan 25 '12 10:01

Heisenbug


People also ask

How many digits can an unsigned int hold?

A 1-byte unsigned integer has a range of 0 to 255. Compare this to the 1-byte signed integer range of -128 to 127. Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large.

How do you print maximum and minimum value of unsigned integer?

printf("%u", ~0); //fills up all bits in an unsigned int with 1 and prints the value. Show activity on this post. printf("%lu",-1);

What is the size of unsigned int?

The int and unsigned int types have a size of four bytes.


1 Answers

Not your ToBinary call is ambiguous, its the constructor call of bitset with an unsigned value. Unfortunately this is a VC++ Bug: http://connect.microsoft.com/VisualStudio/feedback/details/532897/problems-constructing-a-bitset-from-an-unsigned-long-in-the-vc-rc

Edit - Workaround:

template<>
std::string ToBinary<unsigned int>(const unsigned int& value)
{
    const std::bitset<std::numeric_limits<unsigned int>::digits> bs(static_cast<unsigned long long>(value));
    return bs.to_string();
}
like image 188
KasF Avatar answered Oct 16 '22 06:10

KasF