Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a hex string to a byte array

Tags:

c++

string

hex

What is the best way to convert a variable length hex string e.g. "01A1" to a byte array containing that data.

i.e converting this:

std::string = "01A1"; 

into this

char* hexArray; int hexLength; 

or this

std::vector<char> hexArray; 

so that when I write this to a file and hexdump -C it I get the binary data containing 01A1.

like image 290
oracal Avatar asked Jun 23 '13 14:06

oracal


People also ask

How do you convert hex numbers to bytes?

We can convert a hex string to byte array in Java by first converting the hexadecimal number to integer value using the parseInt() method of the Integer class in java. This will return an integer value which will be the decimal conversion of hexadecimal value.

Can we convert string to byte array in Java?

The String class provides three overloaded getBytes methods to encode a String into a byte array: getBytes() – encodes using platform's default charset. getBytes (String charsetName) – encodes using the named charset. getBytes (Charset charset) – encodes using the provided charset.

Is hex a 1 byte?

Now, let's convert a hexadecimal digit to byte. As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.


2 Answers

This implementation uses the built-in strtol function to handle the actual conversion from text to bytes, but will work for any even-length hex string.

std::vector<char> HexToBytes(const std::string& hex) {   std::vector<char> bytes;    for (unsigned int i = 0; i < hex.length(); i += 2) {     std::string byteString = hex.substr(i, 2);     char byte = (char) strtol(byteString.c_str(), NULL, 16);     bytes.push_back(byte);   }    return bytes; } 
like image 37
Chris Vasselli Avatar answered Sep 22 '22 17:09

Chris Vasselli


This ought to work:

int char2int(char input) {   if(input >= '0' && input <= '9')     return input - '0';   if(input >= 'A' && input <= 'F')     return input - 'A' + 10;   if(input >= 'a' && input <= 'f')     return input - 'a' + 10;   throw std::invalid_argument("Invalid input string"); }  // This function assumes src to be a zero terminated sanitized string with // an even number of [0-9a-f] characters, and target to be sufficiently large void hex2bin(const char* src, char* target) {   while(*src && src[1])   {     *(target++) = char2int(*src)*16 + char2int(src[1]);     src += 2;   } } 

Depending on your specific platform there's probably also a standard implementation though.

like image 108
Niels Keurentjes Avatar answered Sep 22 '22 17:09

Niels Keurentjes