-
binary/octal/hexadecimal
hello..
im writing a program that thats suppose to convert and print in a table numbers 1-500 into binary/octal/hexadecimal format..
i not having that much trouble with octal and hexadecimal using a of loop and series of if statements ( i kno not the best way of doin it... its proabably unneccessarily long but it seems to work so far) but im having real trouble with the binary conversions...
is there a function of some sort or any other suggestions that can easily handle this?
thanks
RZArektah
-
Binary Conversion.
This is the recursive function to convert decimal to binary.
long bin_conv(int nNum)
{
int nRem;
long nAns=0;
if (nNum == 0)
return 0;
nRem=nNum%2;
nNum=nNum/2;
nAns=bin_conv(nNum)*10+nRem;
return nAns;
}
Regards,
Mangesh.
-
The standard <iostream> has the capability of printing numbers in binary, hex, or octal.
Code:
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
int a = 16;
cout.flags(ios_base::hex);
cout << "Hexadecimal: " << a << endl;
cout.flags(ios_base::oct);
cout << "Octal: " << a << endl;
cout.flags(ios_base::dec);
cout << "Decimal: " << a << endl;
bitset<8 * sizeof(int)> bin = a;
cout << "Binary: " << bin << endl;
}