JavaScript:需要函数将包含二进制的字符串转换为十六进制,然后转换回二进制

use*_*552 5 javascript binary hex converter

假设我在JavaScript中有一个包含二进制数据的字符串.它可能看起来像这样:

var binary = '00001000010001000101010100001110';
Run Code Online (Sandbox Code Playgroud)

我需要一些可靠的函数将它转换为十六进制字符串,然后再从该十六进制转换回二进制字符串.我知道以下功能

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

// Convert hexadecimal to binary
var binary = parseInt(hex, 16).toString(2)
Run Code Online (Sandbox Code Playgroud)

但我不知道如何一次转换整个字符串.我是否理解我需要将每个4位二进制位一次转换为单个十六进制字符?然后回到二进制I循环每个十六进制字符并再次转换为二进制?

我已经找到了一些在JavaScript中执行此操作的简单示例但无法找到任何示例.

非常感谢

yan*_*han 11

试试这个jsfiddle.

你有更多有趣的功能.不一定是最干净或最有效的,但是:

// 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 };
}
Run Code Online (Sandbox Code Playgroud)


Gia*_*lli 7

为什么不使用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
Run Code Online (Sandbox Code Playgroud)

链接到 jsfiddle在这里

笔记:

  1. 在 中bin2hex,如果您想将小于 4 位的尾随块也转换为十六进制,请替换{4}{1,4}。但是,将结果转换回二进制会产生与原始字符串不同的字符串。例如,来回转换"111101"将产生"11110001".
  2. 在 中hex2bin,二进制值左填充零,以便每个十六进制数字有 4 个二进制数字。