JavaScript:需要函数将包含二进制的字符串转换为十六进制,然后再转换回二进制 [英] JavaScript: Need functions to convert a string containing binary to hex, then convert back to binary

查看:30
本文介绍了JavaScript:需要函数将包含二进制的字符串转换为十六进制,然后再转换回二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

var binary = '00001000010001000101010100001110';

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

I need some reliable functions to convert this into a hexadecimal string, and then convert back from that hexadecimal to a binary string again. I know about the following functions

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

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

但我不确定如何一次转换整个字符串.我是否理解我需要一次将每 4 个二进制位转换为一个十六进制字符?然后回到二进制,我遍历每个十六进制字符并再次转换为二进制?

But I'm not sure how to convert the whole string at once. Am I right in understanding I need to convert each 4 binary bits at a time into a single hexadecimal character? Then to get back to binary I loop through each hexadecimal character and convert to binary again?

我在 JavaScript 中寻找了一些简单的示例,但找不到.

I have hunted for some simple examples doing this in JavaScript but can't find any.

非常感谢

推荐答案

试试这个 jsfiddle.

对您来说更有趣的功能在这里.不一定是最干净或最有效的,但是是的:

The more interesting functions to you are here. Not necessarily the cleanest or most efficient ones, but yea:

// 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 };
}

这篇关于JavaScript:需要函数将包含二进制的字符串转换为十六进制,然后再转换回二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆