Skip to content

Instantly share code, notes, and snippets.

@qxj
Created May 28, 2014 07:13
Show Gist options
  • Save qxj/3bd89345a5a604085842 to your computer and use it in GitHub Desktop.
Save qxj/3bd89345a5a604085842 to your computer and use it in GitHub Desktop.
convert binary string to hex expression each other.
#include <stdlib.h>
#include <string>
namespace {
const char kBin2Hex[] = { "0123456789ABCDEF" };
char Hex2Bin(char ch) {
switch(ch) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A':
case 'a': return 0x0a;
case 'B':
case 'b': return 0x0b;
case 'C':
case 'c': return 0x0c;
case 'D':
case 'd': return 0x0d;
case 'E':
case 'e': return 0x0e;
case 'F':
case 'f': return 0x0f;
}
}
}
std::string bin2hex(const std::string& binary) {
std::string hex;
char chs[3];
const char* ps = binary.data();
for (size_t i = 0; i < binary.size(); ++i) {
unsigned char ch(ps[i]);
chs[0] = kBin2Hex[ch >> 4];
chs[1] = kBin2Hex[ch & 0x0F];
chs[2] = '\0';
hex.append(chs);
}
return hex;
}
std::string hex2bin(const std::string& hex) {
// TODO: hex string length should be even number
// TODO: endian issue
std::string binary;
const char* pt = hex.data();
size_t nlen = hex.size() / 2;
for (size_t i = 0; i < nlen; ++i) {
unsigned char ch = ((Hex2Bin(pt[i*2]) << 4) & 0xF0) + Hex2Bin(pt[i*2+1]);
binary.append(1, ch);
}
return binary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment