Hey everyone,

I'm trying to convert some values to ASCII characters.
I understand that this is possible through means of something like this:

std::cout << (char)0x31 << std::endl; // prints 1
std::cout << (char)0x4C << std::endl; // prints L

However, my problem is that i have char array that contains 4 elements. I'm trying to get each 2 elements from the array and from there use it to get its ASCII values. I took the approach of converting each character to a string and for each pair i added 0x to it. From there i tried to covert each pair to an int and followed by converting it to char so it resembled something similar to above. This did not turn out well as the conversion weren't working.

int main() {

    char buffer[4] = {'3','1', '4', 'C'};
    string ltemp;
    string ltemp2;
    string ltemp3;
    string ltemp4;

    for (int i = 0; i < 2; i++) {
        ltemp = buffer[i];
        ltemp2 = buffer[i+2];

        ltemp3 = ltemp + ltemp2;

        ltemp4 = "0x" + ltemp3;
        cout << "0x" + ltemp3 << endl;
    }


    return 0;
}

Any help on how to approach this will be greatly appreciated

The problem is that a naive atoi like conversion won't work directly with hexadecimal characters because you need to take into account that a-f represent 10-15. That too requires a minor conversion as well to get the values you need. Once you have those values, this formula works to build a 2 digit hexadecimal value:

16 * first_digit_value + second_digit_value

I like to implement that minor conversion with a string search in the set of available digits. For example:

#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int hex_digit(char c)
{
    return string("0123456789abcdef").find(tolower(c));
}

int main()
{
    char buffer[4] = {'3', '1', '4', 'C'};

    for (int i = 0; i < sizeof buffer; i += 2)
    {
        int digit = 16 * hex_digit(buffer[i]) + hex_digit(buffer[i + 1]);

        cout << (char)digit << '\n';
    }
}

Thanks for the awesome response.

man ascii on my bash prompt provides the ascii table, the printable ones that is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.