Convert hex string to byte

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

I've got the following problem:
In one of my programs I receive a string that contains a hex number (e.g. "B4"). Now, I want to convert this "number" into a var of type BYTE. How can this be done

Thanks a lo
Gordon
 
Here you have two solutions:

=======================
#include "stdafx.h"
#include <map>
#include <string>

using namespace std;

map<char, unsigned short int> myMap;

unsigned short int ToHex( char ch )
{
unsigned short int ret = ch - '0';
if( ret <=9 && ret >=0 )
return ret;

return (ch - 'A' ) + 0x0A;
}


int main(int argc, char* argv[])
{
myMap['0'] = 0;
myMap['1'] = 1;
myMap['2'] = 2;
myMap['3'] = 3;
myMap['4'] = 4;
myMap['5'] = 5;
myMap['6'] = 6;
myMap['7'] = 7;
myMap['8'] = 8;
myMap['9'] = 9;
myMap['A'] = 0x0A;
myMap['B'] = 0x0B;
myMap['C'] = 0x0C;
myMap['D'] = 0x0D;
myMap['E'] = 0x0E;
myMap['F'] = 0x0F;

string str = "B4";

unsigned short int n = myMap[ str[0] ] * 16 + myMap[ str[1] ];
unsigned short int m = ToHex( str[0] ) * 16 + ToHex( str[1] );

return 0;
}



Gordon Knote said:
Hi,

I've got the following problem:
In one of my programs I receive a string that contains a hex number (e.g.
"B4"). Now, I want to convert this "number" into a var of type BYTE. How can
this be done?
 
Gordon said:
I've got the following problem:
In one of my programs I receive a string that contains a hex number
(e.g. "B4"). Now, I want to convert this "number" into a var of type
BYTE. How can this be done?

One way is to use the standard C function strtol, specifying a base of
16, and then casting the result from long to byte. For example:

BYTE result = (BYTE)strtol("B4", NULL, 16);

See the documentation of strtol for more details.
 
Gordon Knote said:
Hi,

I've got the following problem:
In one of my programs I receive a string that contains a hex
number (e.g. "B4"). Now, I want to convert this "number" into a var
of type BYTE. How can this be done?

#include <sstream>

typedef unsigned char byte_t;

inline byte_t convertFromHex(const char* str)
{
std::istringstream iss(str);
byte_t byte;
iss >> std::hex >> byte;
if( !iss ) throw my_exception(str, "is not a hex number");
return byte;
}
Thanks a lot
HTH,

Gordon

Schobi

--
(e-mail address removed) is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
 
Back
Top