When trying to convert binary to hexadecimal, I get wrong results in JavaScript and C++.
This is my PHP code:
$f = bin2hex("l¬");
echo $f;
The output is
6cc2ac
In JavaScript, I use this function:
function bin2hex(s){
var i,f =s.length, a =[];
for(i =0;i<f;i++){
a[i] = s.charCodeAt(i).toString(16);
}
return a.join('');
}
The output is
6cac
And this is the C++ code:
std::string bin2hex(const std::string& s)
{
const static char bin2hex_lookup[] = "0123456789abcdef";
unsigned int t=0,i=0,leng=s.length();
std::stringstream r;
for(i=0; i<leng; i++)
{
r << bin2hex_lookup[ s[i] >> 4 ];
r << bin2hex_lookup[ s[i] & 0x0f ];
}
return r.str();
}
Calling the function with
cout << bin2hex("l¬") << endl;
prints
6c c
What is the problem with the JavaScript and the C++ version? Why do they yield different results?