Thread: Binary/Hexadecimal

  1. #1
    Trauts
    Guest

    Binary/Hexadecimal

    How might I write a program that (when compiled with Microsoft Visual C++) would convert a number from base 10 (decimal) to binary or hexadecimal and back?

  2. #2
    Trauts
    Guest
    my email is [email protected]

  3. #3
    Registered User Dr. Bebop's Avatar
    Join Date
    Sep 2002
    Posts
    96
    Here's how to change to binary and hexadecimal, I'll let you write how to change it back.
    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    /* Reverse from K&R */
    void reverse( char *s )
    {
            char c, *i, *j;
            
            for( i = s, j = &s[strlen(s)-1]; i < j; i++, j-- ) {
                    c = *i;
                    *i = *j;
                    *j = c;
            }
    }
    
    long to_binary( int num )
    { 
            int rem; 
            long ans = 0; 
    
            if( num == 0 ) 
                    return 0;
            
            rem = num % 2; 
            num = num / 2; 
            ans = to_binary( num ) * 10 + rem; 
    
            return ans; 
    }
    
    char *to_hex( int num, char *hex, int len )
    {
            char holder[1024] = {0};
            int level = 0;
            
            if( len > 3 ) {
                    do {
                            holder[level] = "0123456789ABCDEF"[num % 16];
                    } while( (num /= 16) && level++ < len );
    
                    reverse( holder );
                    strcpy( hex, "0x" );
                    strcat( hex, holder );
            }
    
            return hex;
    }
    
    int main()
    {
            char p[1024] = {0};
            
            cout<< to_binary( 116 ) <<endl;
            cout<< to_hex( 27, p, 1024 ) <<endl;
    
            return 0;
    }
    Processing error: Stupidity detected.
    ------------------------------
    Dr. Bebop
    Windows XP Professional Ed.
    Microsoft Visual Studio 6

  4. #4
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    error C2871: 'std' : does not exist or is not a namespace

  5. #5
    Registered User Dr. Bebop's Avatar
    Join Date
    Sep 2002
    Posts
    96
    Did you even try to figure out what the problem was before posting an error message with no explanation? I think that's rude, but I'll help anyway. Try changing these three lines
    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    to these two
    Code:
    #include <iostream.h>
    #include <string.h>
    Processing error: Stupidity detected.
    ------------------------------
    Dr. Bebop
    Windows XP Professional Ed.
    Microsoft Visual Studio 6

  6. #6
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    I know to change it to iostream.h, etc. That is basically a given. What I didn't know was that the using namespace std wasn't required. I'm a real beginner at c++ currently

  7. #7
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    I can't seem to figure out how to reverse it... I think it is using your reverse function, but I don't know... I wouldn't have asked for the conversion code in the first place if I could do it.

    How would I get it to go from binary to decimal or hexadecimal?
    How would I get it to go from hexadecimal to decimal or binary?

    cout<< reverse( to_binary ( rvrs ) ) <<endl << "\n";

    would it be something like that?

    I did get it to take the cin earlier so that you can choose the number. That works fine.

  8. #8
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072

    Why reinvent the wheel?

    There are many nice features in C++

    Code:
    cout << hex << 128 << "\n";
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  9. #9
    Registered User
    Join Date
    Sep 2002
    Posts
    417

    Hmmm

    How might I do this?

    Code:
            cout<< to_binary( chosnum ) <<endl;
            cout<< to_hex( chosnum, p, 1024 ) <<endl;
    The first one converts decimal to binary, the second decimal to hexadecimal.

    Exactly how would I use
    Code:
    cout << hex << 128 << "\n";
    with the integer chosnum?

    How do I go from
    1) binary to decimal,
    2) binary to hexadecimal,
    3) hexadecimal to binary,
    4) hexadecimal to decimal.

    Thank you!

  10. #10
    Registered User Dr. Bebop's Avatar
    Join Date
    Sep 2002
    Posts
    96
    The reverse that I posted only reverses the characters in a string. You have to write a function that takes a binary string and manually convert it to hexadecimal and then write another one that takes a hexadecimal number and converts it to decimal. I'm not going to write all of this for you, so your first goal should be to learn how to convert from binary to another number system on paper. If you don't know how to do something at all then how are you going to tell the computer how to do it?
    Processing error: Stupidity detected.
    ------------------------------
    Dr. Bebop
    Windows XP Professional Ed.
    Microsoft Visual Studio 6

  11. #11
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    The computer always stores data as binary, but it routinely
    displays numerical data as decimal. In C++ if you want to display
    the numerical data as hex or oct there are ostream manipulators
    to do so:

    int num = 13;
    cout << num << endl;
    cout << hex << num << endl;
    cout << oct << num << endl;

    Alternatively, you could use printf() with it's formatting string if
    you wish. Either way, however, num is still a decimal, because
    it's declared as an int. If you want to do math in binary, or hex,
    or some other base you need to change num, or at least the value therein. In C/C++ types int, long, short, double, and float
    only decimal values, not other number base systems. Therefore,
    if you want to use/display a value in another base then you often
    use a string to hold the value and display the string.

    char string1[1024];
    cout << "enter a binary number" << endl;
    cin >> string1;
    cout << string1;

    to convert from base 10 to binary you do something like this:
    Code:
    cout << "enter a decimal number less than 1000 and >= 0" << endl;
    cin >> num;
    toBinary(num);
    
    void toBinary(int val)
    {
       char string2[1024];
       char string2[0] = '\0';
       int i = 0;
       while(val > 0)
       { 
          strcat(string2, itoa(val % 2));
          val /= 2;
        }
        string2[i] = '\0';
        //string2 now contains the digits of a binary number as a string 
    of characters with least significant digit on the left and most 
    significant digit on the right.  It's usually displayed the other way 
    around so you have to reverse it, somehow.  Here I use strrev().
        strrev(string2);
        cout << string2;
    }
    To go the other way around you need to do something like this:
    Code:
    char string2[1024];
    cout << "enter a positive binary number" << endl;
    cin >> string2;
    binToDec(string2);
    
    void binToDec(char * string2)
    {
      long num1 = 0;
      int i;
      char temp[2];
      temp[1] = '\0';
      
      for(i = strlen(string2); i >= 0; i--)
      { 
         temp[0] = string2[i];
         num1 += (long) pow(2, (double)atoi(temp));
      }
      cout << "the binary value " << string2 << " in decimal is " << num1;
     }
    You can use a similar algorhythm for hex to dec and back except
    you need to take into account that 10 = a, 11 = b, etc. by using
    another conversion function and an enum or a switch statement
    and that in C++ hex numbers are usally preceded by 0x, which
    can be done as posted above.

    itoa() is non-standard and is in conio.h, which not all compilers
    have. you could use sprintf() or stringstreams or a conversion
    function instead if you wish. strcat() and strrev() are in string.h I
    believe, and pow() is in math.h. atoi() is standard and I believe
    it's in stdlib.h

    All the conversions from char to int, int to string, double to int,
    etc. are a bit of a pain but code is reuseable, so once you've
    done it, you're done, if you have it at your fingertips anyway.
    Sorry about the edits.
    Last edited by elad; 09-11-2002 at 02:04 PM.

  12. #12
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Hmm your post looks weird. I guess it's up to the poster to manually enter newlines within [code] tags.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  13. #13
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398

    Everything IS binary!

    Yeah, like elad said, all the variables are stored in binary form.

    Once the variable is stored as a number, it's easy to display it in Binary, Hex, Decimal, or Octal. It doesn't really get "converted". This makes it easy to write a program that counts-up format.

    So, the key to this problem is converting your text input (A string variable in ASCII format) to a numeric variable. (Of course ASCII variables are stored as binary too, but an ASCII zero does not have the numerical value zero!)

  14. #14
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    Originally posted by Dr. Bebop
    The reverse that I posted only reverses the characters in a string. You have to write a function that takes a binary string and manually convert it to hexadecimal and then write another one that takes a hexadecimal number and converts it to decimal. I'm not going to write all of this for you, so your first goal should be to learn how to convert from binary to another number system on paper. If you don't know how to do something at all then how are you going to tell the computer how to do it?
    I can do it just fine on paper. I don't know enough c++ commands to pull it off.

  15. #15
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    Originally posted by elad
    The computer always stores data as binary, but it routinely displays numerical data as decimal. In C++ if you want to display the numerical data as hex or oct there are ostream manipulators to do so:

    ......


    You can use a similar algorhythm for hex to dec and back except you need to take into account that 10 = a, 11 = b, etc. by using another conversion function and an enum or a switch statement and that in C++ hex numbers are usally preceded by 0x, which can be done as posted above.

    itoa() is non-standard and is in conio.h, which not all compilers have. you could use sprintf() or stringstreams or a conversion function instead if you wish. strcat() and strrev() are in string.h I believe, and pow() is in math.h. atoi() is standard and I believe it's in stdlib.h

    All the conversions from char to int, int to string, double to int, etc. are a bit of a pain but code is reuseable, so once you've done it, you're done, if you have it at your fingertips anyway. Sorry about the edit.

    Thank you!

Popular pages Recent additions subscribe to a feed