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

Convert string to hex then back to string

本文关键字:字符串 转换 然后 十六进制      更新时间:2023-09-26

我必须将一个正在工作的C#函数转换为JavaScript,以便它执行客户端。这是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();

以下是我迄今为止在JavaScript中所掌握的内容。。

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

输入为"0015D1833339"。输出应为"0015D183333A"。但是,JavaScript返回"15d183333a"。我需要保留前面的0。看起来C#函数是用.ToString的"x12"参数实现的。我如何在JavaScript中实现这一点?我需要将其转换为一个整数,将其递增1,然后转换回一个长度为12个字符的字符串。

当你知道你想要的确切长度时,用这样的东西来填充十六进制数输出的简单方法:

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();

本例针对长度为12的字符串,如果需要不同的长度,则需要调整0字符串和子字符串param的长度。