JavaScript: besoin de fonctions pour convertir une chaîne contenant binaire en hexadécimal, puis converti en binaire

Disons que j'ai une chaîne JavaScript avec des données binaires. Cela peut ressembler à ceci:

var binary = '00001000010001000101010100001110'; 

J'ai besoin de certaines fonctions fiables pour convertir ceci en une chaîne hexadécimale, puis revenir de cette hexadécimal à une chaîne binaire. Je connais les fonctions suivantes

 // Convert binary to hexadecimal var hex = parseInt(binaryCharacters, 2).toString(16); // Convert hexadecimal to binary var binary = parseInt(hex, 16).toString(2) 

Mais je ne sais pas très bien comment convertir toute la chaîne à la fois. Est-ce que je comprends bien, j'ai besoin de convertir chaque 4 bits binaires à la fois en un seul caractère hexadécimal? Ensuite, pour revenir en binaire, je boucle chaque caractère hexadécimal et je me convertis en binaire de nouveau?

J'ai cherché quelques exemples simples en JavaScript, mais je ne trouve aucun.

Merci beaucoup

Essayez ce jsfiddle .

Les fonctions les plus intéressantes sont ici. Pas nécessairement les plus propres ou les plus efficaces, mais oui:

 // converts binary string to a hexadecimal string // returns an object with key 'valid' to a boolean value, indicating // if the string is a valid binary string. // If 'valid' is true, the converted hex string can be obtained by // the 'result' key of the returned object function binaryToHex(s) { var i, k, part, accum, ret = ''; for (i = s.length-1; i >= 3; i -= 4) { // extract out in substrings of 4 and convert to hex part = s.substr(i+1-4, 4); accum = 0; for (k = 0; k < 4; k += 1) { if (part[k] !== '0' && part[k] !== '1') { // invalid character return { valid: false }; } // compute the length 4 substring accum = accum * 2 + parseInt(part[k], 10); } if (accum >= 10) { // 'A' to 'F' ret = String.fromCharCode(accum - 10 + 'A'.charCodeAt(0)) + ret; } else { // '0' to '9' ret = String(accum) + ret; } } // remaining characters, i = 0, 1, or 2 if (i >= 0) { accum = 0; // convert from front for (k = 0; k <= i; k += 1) { if (s[k] !== '0' && s[k] !== '1') { return { valid: false }; } accum = accum * 2 + parseInt(s[k], 10); } // 3 bits, value cannot exceed 2^3 - 1 = 7, just convert ret = String(accum) + ret; } return { valid: true, result: ret }; } // converts hexadecimal string to a binary string // returns an object with key 'valid' to a boolean value, indicating // if the string is a valid hexadecimal string. // If 'valid' is true, the converted binary string can be obtained by // the 'result' key of the returned object function hexToBinary(s) { var i, k, part, ret = ''; // lookup table for easier conversion. '0' characters are padded for '1' to '7' var lookupTable = { '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111' }; for (i = 0; i < s.length; i += 1) { if (lookupTable.hasOwnProperty(s[i])) { ret += lookupTable[s[i]]; } else { return { valid: false }; } } return { valid: true, result: ret }; } 

Eh bien, j'ai trouvé un algorithme ici qui a aidé à expliquer comment le faire. De plus, cette page sur Wikipedia a aidé à confirmer les mappages binaires à hexadécimaux 4 bits. Je suis venu avec le code suivant pour le faire. D'autres extraits de code que j'ai trouvé sur le Web ne fonctionnaient pas du tout. Faites-moi savoir si vous apporteriez des améliorations. Vous pourriez probablement même faire une table de recherche directe vraiment en utilisant cette information de Wikipédia qui serait plus rapide.

 var tools = { /** * Converts binary code to hexadecimal string * @param {string} binaryString A string containing binary numbers eg '01001101' * @return {string} A string containing the hexadecimal numbers */ convertBinaryToHexadecimal: function(binaryString) { var output = ''; // For every 4 bits in the binary string for (var i=0; i < binaryString.length; i+=4) { // Grab a chunk of 4 bits var bytes = binaryString.substr(i, 4); // Convert to decimal then hexadecimal var decimal = parseInt(bytes, 2); var hex = decimal.toString(16); // Uppercase all the letters and append to output output += hex.toUpperCase(); } return output; }, /** * Converts hexadecimal code to binary code * @param {string} A string containing single digit hexadecimal numbers * @return {string} A string containing binary numbers */ convertHexadecimalToBinary: function(hexString) { var output = ''; // For each hexadecimal character for (var i=0; i < hexString.length; i++) { // Convert to decimal var decimal = parseInt(hexString.charAt(i), 16); // Convert to binary and add 0s onto the left as necessary to make up to 4 bits var binary = this.leftPadding(decimal.toString(2), '0', 4); // Append to string output += binary; } return output; }, /** * Left pad a string with a certain character to a total number of characters * @param {string} inputString The string to be padded * @param {string} padCharacter The character that the string should be padded with * @param {string} totalCharacters The length of string that's required * @returns {string} A string with characters appended to the front of it */ leftPadding: function(inputString, padCharacter, totalCharacters) { // If the string is already the right length, just return it if (!inputString || !padCharacter || inputString.length >= totalCharacters) { return inputString; } // Work out how many extra characters we need to add to the string var charsToAdd = (totalCharacters - inputString.length)/padCharacter.length; // Add padding onto the string for (var i = 0; i < charsToAdd; i++) { inputString = padCharacter + inputString; } return inputString; } }; 

Pour convertir bin à hex et reverse, j'utilise ces fonctions:

 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 type = "text" id = "bin"> <button onclick = "bintohex()">Convert to Hex</button><br /> Input Hecadecimal: <input type = "text" id = "hex"> <button onclick = "hextobin()">Convert to Bin</button><br /> Results: <div id = "result"></div> 

Pourquoi ne pas utiliser Array.prototype.reduce ?

 var binstr = "00001000010001000101010100001110" function bin2hex(b) { return b.match(/.{4}/g).reduce(function(acc, i) { return acc + parseInt(i, 2).toString(16); }, '') } function hex2bin(h) { return h.split('').reduce(function(acc, i) { return acc + ('000' + parseInt(i, 16).toString(2)).substr(-4, 4); }, '') } console.log(binstr); > 00001000010001000101010100001110 console.log(bin2hex(binstr)); > 0844550e console.log(hex2bin(bin2hex(binstr))); > 00001000010001000101010100001110 

Lien vers jsfiddle ici .

Remarques:

  1. Dans bin2hex , si vous souhaitez convertir également des morceaux de moins de 4 bits en hexagonal, remplacer {4} par {1,4} . Cependant, la conversion du résultat en binaire, produira une chaîne qui diffère de l'original. Par exemple, la conversion en avant et en arrière "111101" produirait "11110001" .
  2. Dans hex2bin , les valeurs binaires sont remises à zéro avec des zéros afin d'avoir 4 chiffres binaires pour chaque chiffre hexadécimal.