Transform 'B' into 0Xb

Transform 'B' into 0Xb

I'm trying to decode ISO8583 message bitmap in a fast way. Supposing the first bitmap char is a 'B', I want to convert it to hex value 0xB (11 in decimal) to after that, check what bits are flagged. The last part I'm doing this way:

for(int i = 0; i < 4; i++){
    std::cout << (value &(1 << i));
}

Because bitmaps and messages are long I'm trying to decoding fast. I saw some SO posts using std::hex and std::stringstream. But using this or lookup tables it isn't too much?

1

2 Answers

What I want is convert from 'B' to hex value 0xB, which is 11

So, you want to interpret B as hexadecimal digit and get numerical value, rather than "convert it to hexadecimal representation". Following works for any base (up to base 36) and with upper and lower case digits:

 int value =
     (c >= '0' && c <= '9') ? (c - '0')       :
     (c >= 'A' && c <= 'Z') ? (c - 'A' + 0xA) :
     (c >= 'a' && c <= 'z') ? (c - 'a' + 0xA) :
     -1; // error

You can substitute z with f if you want the error value when input is not a hexadecimal digit.


Old answer:

Characters are encoded as numbers. What numerical value represents which character is determined by the character encoding.

"Hex representation" of a number is a string of characters. Those characters represent the hexadecimal digits of the number individually. The numerical values of the characters in the hex representation are meaningless without the context of the character encoding.

Supposing the first bitmap char is a 'B', I want to convert it to hex representation (Transform 'B' into 0xB)

#include <string>
using namespace std::string_literals;

int main() {
    char c = 'B';
    std::string hex = "0x"s + c; // now hex is "0xB"
}

It would indeed be quite inefficient to first convert B to an integer, and then back to hex representation with std::stringstream if all you want is to add the prefix.

3

Create an array that acts as a map.

int hexNumbers[] = { 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };

and then use it to as below:

if ( c >= 'A' && c <= 'F' )
{
   number = hexNumbers[c-'A'];
}
else if ( c >= 'a' && c <= 'f' )
{
   number = hexNumbers[c-'a'];
}

You can do it without a map also:

if ( c >= 'A' && c <= 'F' )
{
   number = 0xA + (c-'A');
}
else if ( c >= 'a' && c <= 'f' )
{
   number = 0xA + (c-'a');
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.