Here's something I put together just now; whilst I don't know enough
to make this act the same way std::hex and std::dec does, this works
quite well enough for me, but I think I could improve on this.
Suggestions and flames both welcome. To use, try this:
unsigned char ch = 0x80;
std::cout << std::binary(ch) << "\n";
So, here's the code as follows:
namespace std
{
template <typename _T>
struct _binary { std::string _digits; };
template <typename T>
inline _binary<T> binary(T n)
{
_binary<T> __binary;
int bits = sizeof(n);
switch (bits)
{
case 1 : bits = 7; break;
case 2 : bits = 15; break;
case 4 : bits = 31; break;
// add more if necessary
}
for (int i = bits; i >= 0; i--)
{
if ((n >> i) & 1)
__binary._digit s.append("1");
else
__binary._digit s.append("0");
}
return __binary;
}
template <typename T>
ostream& operator<<(ostr eam& stream, _binary<T> __binary)
{
stream << __binary._digit s;
return stream;
}
}
--
Take a nap, it saves lives.
to make this act the same way std::hex and std::dec does, this works
quite well enough for me, but I think I could improve on this.
Suggestions and flames both welcome. To use, try this:
unsigned char ch = 0x80;
std::cout << std::binary(ch) << "\n";
So, here's the code as follows:
namespace std
{
template <typename _T>
struct _binary { std::string _digits; };
template <typename T>
inline _binary<T> binary(T n)
{
_binary<T> __binary;
int bits = sizeof(n);
switch (bits)
{
case 1 : bits = 7; break;
case 2 : bits = 15; break;
case 4 : bits = 31; break;
// add more if necessary
}
for (int i = bits; i >= 0; i--)
{
if ((n >> i) & 1)
__binary._digit s.append("1");
else
__binary._digit s.append("0");
}
return __binary;
}
template <typename T>
ostream& operator<<(ostr eam& stream, _binary<T> __binary)
{
stream << __binary._digit s;
return stream;
}
}
--
Take a nap, it saves lives.
Comment