[removed] Need functions to convert a string containing binary to hex, then convert back to binary

前端 未结 4 891
醉梦人生
醉梦人生 2020-11-28 11:40

Lets say I have a string in JavaScript with binary data in it. It may look like this:

var binary = \'00001000010001000101010100001110\';

I

4条回答
  •  我在风中等你
    2020-11-28 12:12

    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.

提交回复
热议问题