Javascript 将字符串编码为 HEX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36637146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:20:24  来源:igfitidea点击:

Encode String to HEX

javascriptutf-8hex

提问by John Pangilinan

i have my function to convert string to hex:

我有将字符串转换为十六进制的函数:

function encode(str){
    str = encodeURIComponent(str).split('%').join('');
    return str.toLowerCase();
}

example:

例子:

守护村子

守护村子

alert(encode('守护村子'));

alert(encode('守护村子'));

the output would be:

输出将是:

e5ae88e68aa4e69d91e5ad90

e5ae88e68aa4e69d91e5ad90

It works on Chinese characters. But when i do it with English letters

它适用于汉字。但是当我用英文字母来做的时候

alert(encode('Hello World'));

alert(encode('Hello World'));

it outputs:

它输出:

hello20world

hello20world

I have tried this for converting string to hex:

我已经尝试过将字符串转换为十六进制:

function String2Hex(tmp) {
    var str = '';
    for(var i = 0; i < tmp.length; i++) {
        str += tmp[i].charCodeAt(0).toString(16);
    }
    return str;
}

then tried it on the Chinese characters above, but it outputs the UTF-8 HEX:

然后在上面的中文字符上尝试了一下,但它输出了UTF-8 HEX:

5b8862a467515b50

5b8862a467515b50

not the ANSI Hex:

不是 ANSI 十六进制:

e5ae88e68aa4e69d91e5ad90

e5ae88e68aa4e69d91e5ad90

I also have searched converting UFT8 to ANSI but no luck. Anyone could help me? Thanks!

我也搜索过将 UFT8 转换为 ANSI 但没有运气。任何人都可以帮助我吗?谢谢!

采纳答案by John Pangilinan

I have solve this by downloading utf8.js

我已经通过下载解决了这个问题 utf8.js

https://github.com/mathiasbynens/utf8.js

https://github.com/mathiasbynens/utf8.js

then using the String2Hexfunction above:

然后使用String2Hex上面的函数:

alert(String2Hex(utf8.encode('守护村子')));

alert(String2Hex(utf8.encode('守护村子')));

gives me the output i want:

给我我想要的输出:

e5ae88e68aa4e69d91e5ad90

e5ae88e68aa4e69d91e5ad90

回答by Cassio

const myString = "This is my string to be encoded/decoded";
const encoded = new Buffer(myString).toString('hex'); // encoded === 54686973206973206d7920737472696e6720746f20626520656e636f6465642f6465636f646564
const decoded = new Buffer(encoded, 'hex').toString(); // decoded === "This is my string to be encoded/decoded"

回答by hannad rehman

this should work

这应该有效

var str="some random string";
var result = "";
    for (i=0; i<str.length; i++) {
        hex = str.charCodeAt(i).toString(16);
        result += ("000"+hex).slice(-4);
    }

回答by Daniel Earwicker

As a self-contained solution in functional style, you can encode with:

作为功​​能风格的独立解决方案,您可以使用以下方式进行编码:

plain.split("")
     .map(c => c.charCodeAt(0).toString(16))
     .join("");

The spliton an empty string produces an array with one character (or rather, one UTF-16 codepoint) in each element. Then we can map each to a HEX string of the character code.

split上一个空字符串产生在每个元件中的一个字符(或更确切地说,一个UTF-16码点)的阵列。然后我们可以将每个映射到字符代码的 HEX 字符串。

Then to decode:

然后解码:

hex.split(/(\w\w)/g)
   .filter(p => !!p)
   .map(c => String.fromCharCode(parseInt(c, 16)))
   .join("")

This time the regex passed to splitcaptures groups of two characters, but this form of splitwill intersperse them with empty strings (the stuff "between" the captured groups, which is nothing!). So filteris used to remove the empty strings. Then mapdecodes each character.

这次传递给的正则表达式split捕获了两个字符的组,但是这种形式的split将用空字符串散布它们(捕获组“之间”的东西,这没什么!)。Sofilter用于删除空字符串。然后map解码每个字符。

回答by Ruben Reyes

If you want to properly handle UTF8 strings you can try these:

如果你想正确处理 UTF8 字符串,你可以试试这些:

    function utf8ToHex(str) {
      return Array.from(str).map(c => 
        c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) : 
        encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
      ).join('');
    },
    function hexToUtf8: function(hex) {
      return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
    }

Demo: https://jsfiddle.net/lyquix/k2tjbrvq/

演示:https: //jsfiddle.net/lyquix/k2tjbrvq/