Thread: binary/octal/hexadecimal

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    19

    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

  2. #2
    Registered User Mangesh's Avatar
    Join Date
    Sep 2001
    Posts
    18

    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.

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    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;
    }
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed