# C++ Notes: Bit Ops - Convert to hex

This program reads integers and prints them in hexadecimal, using the shift and "and" operators to extract the relevant digits. Note: This requires knowledge of character arrays. The problems require use of functions.

    // Read ints and print their hex representations
    // Note sizeof(int) returns number of bytes in an int.

    #include <iostream>
    using namespace std;

    void main() {
        int n;
        while (cin >> n) {
            cout << "decimal: " << n << endl;

            //--- Print hex with leading zeros
            cout << "hex    : ";
            for (int i=2*sizeof(int) - 1; i>=0; i--) {
                cout << "0123456789ABCDEF"[((n >> i*4) & 0xF)];
            }
            cout << endl << endl;
        }
    }

## Exercises

Here are some modifications that could be made to this code.

1. This program writes the digits to `cout`. A more general solution is to write the conversions as functions which put their output into a character array as c-strings. Write these conversions as functions with the following prototypes:

           void intToBinary(char result[], int n);
           void intToHex(char result[], int n);

           // A call might look like this:
           char binary[50]; // big enough to hold an int with spaces.
           . . .
           while (cin >> n) {
              intToBinary(binary, n);  // produce binary character string.
              cout << binary << " has " < strlen(binary)
                   << " digits." << endl;
           }

   There is a big difference between the hex conversion and the binary conversion. The hex conversion writes a char to cout while the binary conversion writes an int. It's necessary to put a char in the output array of the function of course.