Lets say I have a string in JavaScript with binary data in it. It may look like this:
var binary = \'00001000010001000101010100001110\';
I
To convert bin to hex and reverse i use these functions:
function bintohex()
{
mybin = document.getElementById('bin').value;
z = -1; number = 0;
for(i = mybin.length; i > -1; i--)
{
//Every 1 in binary string is converted to decimal and added to number
if(mybin.charAt(i) == "1"){
number += Math.pow(2, z);
}
z+=1;
}
// Return is converting decimal to hexadecimal
document.getElementById('result').innerHTML = number.toString(16);
}
function hextobin()
{
mybin = "";
/// Converting to decimal value and geting ceil of decimal sqrt
myhex = document.getElementById('hex').value;
mydec = parseInt(myhex, 16);
i = Math.ceil( Math.sqrt(mydec) );
while(i >= 0)
{
if(Math.pow(2, i) <= mydec){
mydec = mydec-Math.pow(2, i);
mybin += "1";
}else if(mybin != "")
mybin = mybin + "0";
i = i-1;
}
document.getElementById('result').innerHTML = mybin;
}
Input binary:
Input Hecadecimal:
Results:
Don't forget to check your answer.