#include <iostream>
#include <sstream>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
char hx[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
inline int hextoint(char in) {
int const x = in;
return (x <= 57) ? x - 48 : (x <= 70) ? (x - 65) + 0x0a : (x - 97) + 0x0a;
}
string binaryToHEX(const string& input) {
size_t len = input.length();
if (len % 4 != 0) {
return "";
}
string output = string(len / 4, '0');
size_t outputoffset = 0;
for (size_t i = 0; i < len; i += 4) {
int val = 0;
for (size_t j = 0; j < 4; j++) {
if (input[i + j] == '1') {
val += (1 << (3 - j));
}
}
output[outputoffset++] = hx[val];
}
return output;
}
string HEXToBinary(const string& input) {
size_t len = input.length();
string output = string(len * 4, '0');
for (size_t i = 0; i < len; i++) {
unsigned int offset = i * 4;
int val = hextoint(input[i]);
for (size_t j = 0; j < 4; j++) {
output[offset + 3 - j] = ((val & (1 << j)) != 0) ? '1' : '0';
}
}
return output;
}
int main() {
cout << binaryToHEX("1010101101000010") << endl;
cout << HEXToBinary("AB42") << endl;
system("pause");
return 1;
}
I copied the hextoint function from someone else on here, but I cannot find the post.