I
Immortal Nephi
I am curious. Why don't iostream libary support binary conversion?
Let's say for example. You want to use "cout << hex << xx << endl"
What about "cout << binary << xx << endl"? No such binary exist.
Take a look at my code below. First example is the best option, but I
prefer second example. Do you have other ways that binary will be
supported?
string convBase(unsigned long v, long base)
{
string digits = "0123456789abcdef";
string result;
if((base < 2) || (base > 16)) {
result = "Error: base out of range.";
}
else {
do {
result = digits[v % base] + result;
v /= base;
}
while(v);
}
return result;
}
int main()
{
// First Example
unsigned long x = 0xABCD;
cout << "???: " << convBase(x,4) << endl;
cout << "Hex: " << convBase(x,16) << endl;
cout << "Decimal: " << convBase(x,10) << endl;
cout << "Octal: " << convBase(x,8) << endl;
cout << "Binary: " << convBase(x,2) << endl;
cout << "Test: " << convBase(x,32) << endl;
// Second Example
int i = 0x0203;
std::string s;
std:stringstream out;
out << hex << i;
s = out.str();
cout << "-->" << s << "\n" << out.str() << endl;
return 0;
}
Let's say for example. You want to use "cout << hex << xx << endl"
What about "cout << binary << xx << endl"? No such binary exist.
Take a look at my code below. First example is the best option, but I
prefer second example. Do you have other ways that binary will be
supported?
string convBase(unsigned long v, long base)
{
string digits = "0123456789abcdef";
string result;
if((base < 2) || (base > 16)) {
result = "Error: base out of range.";
}
else {
do {
result = digits[v % base] + result;
v /= base;
}
while(v);
}
return result;
}
int main()
{
// First Example
unsigned long x = 0xABCD;
cout << "???: " << convBase(x,4) << endl;
cout << "Hex: " << convBase(x,16) << endl;
cout << "Decimal: " << convBase(x,10) << endl;
cout << "Octal: " << convBase(x,8) << endl;
cout << "Binary: " << convBase(x,2) << endl;
cout << "Test: " << convBase(x,32) << endl;
// Second Example
int i = 0x0203;
std::string s;
std:stringstream out;
out << hex << i;
s = out.str();
cout << "-->" << s << "\n" << out.str() << endl;
return 0;
}