user2544408
user2544408

Reputation: 1

Trying to write a C++ function to un-hex encode a 8 bit char and turn it into an integer

I have a C++ function that converts a unsigned long into a 8 bit hex char string. I need to come up with a reverse function that takes a 8 bit hex char string and converts it into an unsigned integer representing it's bytes.

Original UINT -> char[8] method:

std::string ResultsToHex( unsigned int EncodeResults)
{

        std::cout << "UINT Input ==>";
        std::cout << EncodeResults;
        std:cout<<"\n";

        char _HexCodes[] = "0123456789ABCDEF";
        unsigned int HexAccum = EncodeResults;
        char tBuf[9];
        tBuf[8] = '\0';
        int Counter = 8;
        unsigned int Mask = 0x0000000F;
        char intermed;

        // Start with the Least significant digit and work backwards

        while( Counter-- > 0 )
        {

            // Get the hex digit
            unsigned int tmp = HexAccum & Mask;

            intermed = _HexCodes[tmp];

            tBuf[Counter] = intermed;

            // Next digit
            HexAccum = HexAccum >> 4;
        }

        std::cout << "Hex char Output ==>";
        std::cout << tBuf;
        std::cout << "\n";

        return std::string(tBuf);
    }

And here is the function I am trying to write that would take a char[8] as input and convert into a UINT:

 unsigned int ResultsUnhex( char tBuf[9])
{
        unsigned int result = 0;
        std::cout << "hex char Input ==>";
        std::cout << tBuf;
        std:cout<<"\n";

        //CODE TO CONVERT 8 char (bit) hex char into unsigned int goes here......
        //
        // while() {}
        //
        ///


        std::cout << "UINT Output ==>";
        std::cout << result;
        std::cout << "\n";

        return result;
    }

I am new to bit shifts, any help would be greatly appreciated :).

Upvotes: 0

Views: 1883

Answers (2)

Captain Obvlious
Captain Obvlious

Reputation: 20063

You need to scan the string and convert each hexadecimal character back to it's corresponding 4 bit binary value. You can do this with a simple set of if statements that checks the character to see if it's valid and if so convert it back.

After a character has been converted, shift your result variable left by 4 bits then stuff the converted value into the lower 4 bits of the result.

#include <stdexcept>

unsigned int ConvertHexString(char *str)
{
    unsigned int result = 0;
    while(*str)
    {
        char ch = *str++;

        // Check for 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9
        if(ch >= '0' && ch <= '9')
        {
            ch -= '0';
        }
        // Check for a, b, c, d, e, f
        else if(ch >= 'a' && ch <= 'f')
        {
            ch = 10 + (ch - 'a');
        }
        // Check for A, B, C, D, E, F
        else if(ch >= 'A' && ch <= 'F')
        {
            ch = 10 + (ch - 'A');
        }
        // Opps! Invalid character
        else
        {
            throw std::invalid_argument("Unknown character in hex string");
        }


        // Mmmm! Stuffing! Don't forget to check for overflow!
        result = (result << 4) | ch;
    }

    return result;
}

There are several ways to do this but I figured a simple example to get you started would be more helpful.

Obligatory example using the conversion function.

#include <iostream>
int main()
{
    std::cout
        << std::hex
        << ConvertHexString("1234567")
        << ConvertHexString("90ABCDEF")
        << std::endl;
}

Outputs...

123456790abcdef

Upvotes: 2

quetzalcoatl
quetzalcoatl

Reputation: 33536

Why do you do it manually? There's plenty of tools that do that for you. For example, stringstream.

This converts an int to a hex-string:

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

[code copied from Integer to hex string in C++ - please see that thread, there's plenty of examples. Upvote there instead of here.]

Add to that "0x" and some field-width manipulators and you may reduce the ResultsToHex to three..five lines.

The stringstream also works the other way. Using >> operator you can just as easily read a hexstring into an integer variable. [Converting Hexadecimal to Decimal, Hex character to int in C++, convert hex buffer to unsigned int, ...]

Upvotes: 0

Related Questions