Skip to content

Instantly share code, notes, and snippets.

@Lima-X
Last active September 13, 2020 11:27
Show Gist options
  • Save Lima-X/d7799688a7465bd9532cf627a76d51a3 to your computer and use it in GitHub Desktop.
Save Lima-X/d7799688a7465bd9532cf627a76d51a3 to your computer and use it in GitHub Desktop.
A fast C++ Hexconverter-Class using a Lookuptable (for ANSI and lowercase only)
class HexConv {
public:
HexConv() {
// Setup HexTable
for (char i = 0; i < 10; i++)
m_HexTable[i] = i + '0';
for (char j = 0; j < 6; j++) {
m_HexTable[j + 10] = j + 'a';
m_HexTable[j + ('a' - '0')] = j + ('0' + 10);
}
}
void BinToHex( //
void* pData, // Data to be converted
size_t nData, // Size of Data
char* sz // Target String to Fill
) const {
for (unsigned int i = 0; i < nData; i++) {
sz[i * 2] = m_HexTable[((unsigned char*)pData)[i] >> 4];
sz[(i * 2) + 1] = m_HexTable[((unsigned char*)pData)[i] & 0xf];
}
sz[nData * 2] = '\0';
}
void HexToBin( //
char* sz, // String to be converted
void* pOut // Target array to fill
) const {
while (*sz != '\0'
*(*(unsigned char**)&pOut)++ = ((m_HexTable[*sz++ - '0'] - '0') << 4) + (m_HexTable[*sz++ - '0'] - '0');
}
private:
char m_HexTable[('a' - '0') - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment