I have the following string in both my PHP and C++ scripts:
152F302436152F302435152F302434152F302433152F302433
In PHP I use the built-in hex2bin function as:
<?php
$HEXString = "152F302436152F302435152F302434152F302433152F302433";
echo hex2bin($HEXString);
//Outputs: /0$6/0$5/0$4/0$3/0$3
?>
However, in C++ I use the following functions to accomplish the same with a complete other result:
const char* HexCharToBin(char c) {
char cUpper = toupper(c);
if (cUpper == '0') return "0000";
else if (cUpper == '1') return "0001";
else if (cUpper == '2') return "0010";
else if (cUpper == '3') return "0011";
else if (cUpper == '4') return "0100";
else if (cUpper == '5') return "0101";
else if (cUpper == '6') return "0110";
else if (cUpper == '7') return "0111";
else if (cUpper == '8') return "1000";
else if (cUpper == '9') return "1001";
else if (cUpper == 'A') return "1010";
else if (cUpper == 'B') return "1011";
else if (cUpper == 'C') return "1100";
else if (cUpper == 'D') return "1101";
else if (cUpper == 'E') return "1110";
else if (cUpper == 'F') return "1111";
else return "0000";
}
string HexToBin(const string& hex) {
string bin;
for (unsigned i = 0; i != hex.length(); ++i) {
bin += HexCharToBin(hex[i]);
}
return bin;
}
The code in C++:
cout << HexToBin("152F302436152F302435152F302434152F302433152F302433") << endl;
//Outputs: 00010101001011110011000000100100001101100001010100101111001100000010010000110101000101010010111100110000001001000011010000010101001011110011000000100100001100110001010100101111001100000010010000110011
I want C++ to achieve the same string as PHP returns. What am I doing wrong here?