DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

George Jempty
George Jempty

Posted on

Hexadecimal addition in a MAC address context

I don't answer a lot of StackOverflow questions any more, they are mostly so specialized, or when they are something I can answer a lot of the time while I'm composing my answer, two or three new answers are posted all similar to my intended answer. On the other hand sometimes when I truly do want to answer I cannot do so at that very moment, for I'm at work, or, as was the case last night, was out with my wife for the evening with only my tablet which IMO is hardly sufficient for writing a properly tested SO answer with, though your experience may be different.

In any case, I often mark such questions as favorites and then review later at a more convenient time, which is what I did with last night's. I won't go into the details here, it's all in the StackOverflow post, so the link follows. My answer doesn't do a lot that's different from the others though, biased as I am, I like to think of it as a clean synthesis of those ideas that uses some more modern Javascript techniques than the others.

https://stackoverflow.com/questions/59515305/incrementing-hexadecimal-string-from-mac-address/59521438#59521438

Actually for the sake of being more complete and not forcing readers to follow the above link, here's my code, though you may still need to refer to the question for the requirements.

const macAddrs = [
  '84:1D:A2:B9:A3:D0',
  '84:1D:A2:B9:A3:99',
  '84:1D:A2:B9:A3:AF',
  '84:1D:A2:B9:A3:FF'
];

const addrsIncr = macAddrs.map(addr => {
  let addrPrefix = addr.slice(0, 15); // everything up to and including last colon
  let modulusIncrLastOctet = (parseInt(addr.slice(15), 16) + 1) % 256; // converts FF to 01
  return addrPrefix + modulusIncrLastOctet.toString(16).padStart(2, 0).toUpperCase();
});

Top comments (0)

πŸ‘‹ New to DEV?

Head over to our Welcome Thread and tell us a bit about yourself!