简体   繁体   English

将字符串转换为十六进制,然后返回字符串

[英]Convert string to hex then back to string

I have to convert a working C# function to JavaScript so it executes client-side. 我必须将一个有效的C#函数转换为JavaScript,以便它执行客户端。 Here's the C#... 这是C#...

// convert the cmac into a hex number so we can increment it and get the emac
long emacLong = Convert.ToInt64(_cmac, 16) + 1;
emac = emacLong.ToString("x12").ToUpper();

Here's what I have so far in JavaScript.. 这是我到目前为止在JavaScript中所拥有的。

var emac = parseInt(cmac, 16) + 1;
emac = emac.toString(16);

The input is "0015D1833339". 输入为“ 0015D1833339”。 The output should be "0015D183333A". 输出应为“ 0015D183333A”。 However, the JavaScript returns "15d183333a". 但是,JavaScript返回“ 15d183333a”。 I need to retain the leading 0's. 我需要保留前导0。 Looks like the C# function accomplishes this with the "x12" parameter of .ToString. 看起来C#函数使用.ToString的“ x12”参数完成了此任务。 How do I accomplish this in JavaScript? 如何在JavaScript中完成此操作? I need to convert it to an integer, increment it by 1 and then convert back to a string with a length of 12 characters. 我需要将其转换为整数,将其递增1,然后转换回长度为12个字符的字符串。

Easy way to pad hex number output when you know the exact length you desire is with something like this: 当您知道所需的确切长度时,使用简单的方法填充十六进制数字输出的方法如下:

var emac = parseInt(cmac, 16) + 1;
emac = ("000000000000" + emac.toString(16)).substr(-12);

// or if you MUST have all caps....
emac = ("000000000000" + emac.toString(16)).substr(-12).toUpperCase();

This example is for length 12, if you need a different length, you would adjust the length of the 0 string and the substr param. 此示例适用于长度12,如果需要其他长度,则可以调整0字符串和substr参数的长度。

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

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