简体   繁体   English

如何使用 JavaScript 转换预期的十六进制值 output

[英]how to convert hexadecimal value expected output using JavaScript

I tried a lot of ways, but none give the expected result.我尝试了很多方法,但没有一个给出预期的结果。

Input: 04:3d:54:a2:68:61:80输入: 04:3d:54:a2:68:61:80

Expected output: 01193333618139520预计 output: 01193333618139520

How would I go about this in JS?我如何在 JS 中使用 go?

 const value = `04:3d:54:a2:68:61:80` const barcode = parseInt(value.replace(':', ''), 16) console.log(barcode) // 1085

The problem is that you are using replace instead of replaceAll问题是您使用的是replace而不是replaceAll

 const value = `04:3d:54:a2:68:61:80` const barcode = parseInt(value.replaceAll(':', ''), 16) console.log(barcode)

As Lian suggests, you can also achieve that with replace(/:/g, '')正如Lian建议的那样,您也可以使用replace(/:/g, '')来实现

And therefore get better browser compatibility并因此获得更好的浏览器兼容性

 const value = `04:3d:54:a2:68:61:80` const barcode = parseInt(value.replace(/:/g, ''), 16) console.log(barcode)

First remove colons, then use parseInt(myHex, 16).首先删除冒号,然后使用 parseInt(myHex, 16)。

const myHex = '04:3d:54:a2:68:61:80';

function hexToDecimal(hexadecimal) {
  return parseInt(hexadecimal.replaceAll(':', ''), 16);
}

console.log(hexToDecimal(myHex));

Use the parseInt function, passing your input as the first parameter and 16 (since hexadecimal is base-16) as the second.使用parseInt function,将您的输入作为第一个参数传递,将16 (因为十六进制是以 16 为底)作为第二个参数传递。

let input = '04:3d:54:a2:68:61:80';
const inputParsed = parseInt(input.replace(/:/g, ''), 16); // 1193333618139520

If you need the leading zero for some reason you can do something like this:如果你出于某种原因需要前导零,你可以这样做:

const inputParsedStr = `${inputParsed.toString().startsWith('0') ? '' : '0'}${inputParsed}`; // '01193333618139520'

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

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