0

I have to convert a working C# function to JavaScript so it executes client-side. Here's the 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..

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

The input is "0015D1833339". The output should be "0015D183333A". However, the JavaScript returns "15d183333a". I need to retain the leading 0's. Looks like the C# function accomplishes this with the "x12" parameter of .ToString. How do I accomplish this in 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.

cacosta
  • 77
  • 2
  • 11

1 Answers1

2

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.

Anthony Patton
  • 595
  • 3
  • 10
  • You only need eleven `0`s, and you forgot the `.toUpperCase()` ;) – Andrew Morton Dec 15 '15 at 19:57
  • I didn't add toUpperCase because OP didn't specifically ask for it. But your right about only needing eleven. Kept it consistent with the substr length for simplicity. – Anthony Patton Dec 15 '15 at 20:04
  • OP stated: *The output should be "0015D183333A"*. Come on, I'm waiting to give you a +1 for posting the answer just before I was going to :) – Andrew Morton Dec 15 '15 at 20:06
  • Perfecto! Works like a charm! I can handle the .toUpperCase(), but thanks for pointing out my omission. ;) – cacosta Dec 15 '15 at 20:13