lotto 1988
lotto 1988

Reputation: 33

C++ check If a hexadecimal consists of ABCDEF1 OR 0

I have written a program below that converts a string to an int and then converts the decimal number to hexadecimal. I'm struggling to check if the hexadecimal consists only of these characters A, B, C, D, E, F, 1, 0. If so set a flag to true or false.

#include<iostream>
#include <stdlib.h>
#include <string>
#include <sstream>


string solution(string &S){

    int n = stoi(S);
    int answer;

    cout << "stoi(\"" << S << "\") is "
            << n << '\n';

    //decToHexa(myint);
    // char array to store hexadecimal number
    string hexaDeciNum[100];

    // counter for hexadecimal number array
    int i = 0;
    while(n!=0)
    {
        // temporary variable to store remainder
        int temp  = 0;

        // storing remainder in temp variable.
        temp = n % 16;

        // check if temp < 10
        if(temp < 10)
        {
            hexaDeciNum[i] = temp + 48;
            i++;
        }
        else
        {
            hexaDeciNum[i] = temp + 55;
            i++;
        }

        n = n/16;
    }

    // printing hexadecimal number array in reverse order
    for(int j=i-1; j>=0; j--){
        cout << hexaDeciNum[j] << "\n";


    return "";
}

int main() {

string word = "300";

cout << solution(word);

return 0;

}

Upvotes: 0

Views: 711

Answers (1)

Aconcagua
Aconcagua

Reputation: 25526

OK, it is not the exact answer to what you are asking for, but it is a valuable alternative approach for the entire problem of conversion:

char letter(unsigned int digit)
{
    return "0123456789abcdefg"[digit];
    // alternatively upper case letters, if you prefer...
}

Now you don't have to differenciate... You can even use this approach for inverse conversion:

int digit(char letter)
{
    int d = -1; // invalid letter...
    char const* letters = "0123456789abcdefABCDEF"; 
    char* l = strchr(letters, letter);
    if(l)
    {
       d = l - letters;
       if(d >= 16)
           d -= 6;
    }
    // alternatively upper case letters, if you prefer...
}

Another advantage: This works even on these strange character sets where digits and letters are not necessarily grouped into ranges (e. g. EBCDIC).

Upvotes: 1

Related Questions