Skip to content

Instantly share code, notes, and snippets.

@vurdalakov
Created October 6, 2016 08:18
Show Gist options
  • Save vurdalakov/fdc88a2f28d3d4f500b7b73a500fd886 to your computer and use it in GitHub Desktop.
Save vurdalakov/fdc88a2f28d3d4f500b7b73a500fd886 to your computer and use it in GitHub Desktop.
Convert hex string to binary array
#pragma once
#include <windows.h>
#include <string>
// Helper functuion used by hex2bin() function.
inline int hex2byte(char c)
{
if ((c >= '0') && (c <= '9'))
{
return c - '0';
}
if ((c >= 'A') && (c <= 'F'))
{
return c - 'A' + 10;
}
if ((c >= 'a') && (c <= 'f'))
{
return c - 'a' + 10;
}
return -1;
}
// Converts a hex string to a binary array.
// Returns NULL if string is not a hex array.
// NOTE: it's caller responsibility to free returned array with "delete[]".
inline unsigned char* hex2bin(const char* hex, size_t hexSize = -1)
{
if (NULL == hex)
{
return NULL;
}
if (hexSize < 0)
{
hexSize = strlen(hex);
}
if ((hexSize % 2) != 0)
{
return NULL;
}
size_t binSize = hexSize / 2;
unsigned char* bin = new unsigned char[binSize];
size_t k = 0;
for (size_t i = 0; i < binSize; i++)
{
int n1 = hex2byte(hex[k]);
k++;
int n2 = hex2byte(hex[k]);
k++;
if ((n1 < 0) || (n2 < 0))
{
delete[] bin;
return NULL;
}
bin[i] = (n1 << 4) | n2;
}
return bin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment