简体   繁体   English

Javascript:十六进制至十进制的字符串

[英]Javascript: String with hex to decimal

I've got this string containing multiple hexadecimal numbers: 我有一个包含多个十六进制数字的字符串:

let input = '\\x01\\x01\\x02\\x01';

I would like to see this transformed into: 1121 (the decimal representation of each hex number) 我希望将其转换为: 1121 (每个十六进制数字的十进制表示)

How would I go about this? 我将如何处理? I've tried numerous things, but the only output I get are some diamond shapes with a questionmark inside of it or syntax errors. 我已经尝试了很多事情,但是我得到的唯一输出是一些带有问号或语法错误的菱形形状。 Many thanks in advance! 提前谢谢了!

Here is a simple method that escapes the string, removes empty elements, converts each number to is decimal digit, joins it as a string, and then converts the final result to a number. 这是一个简单的方法,可以对字符串进行转义,删除空元素,将每个数字转换为十进制数字,将其作为字符串连接,然后将最终结果转换为数字。

 function convert(string) { string = escape(string); string = string.split(/%/).filter(e=>e); string = string.map(e => +("0x"+e)); return +string.join(""); } // Test case var decimal = convert('\\x01\\x01\\x02\\x01'); console.log(decimal); 

To be able to work with the escape sequences itself and not the resulting whitespace, you habe to use String raw then you can replace: 为了能够使用转义序列本身而不是最终的空格,您可以使用String raw来替换:

let input = String.raw`\x01\x01\x02\x01`;

console.log(
  input
   .replace(/\\x01/g, "1")
   .replace(/\\x02/g, "2")
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM