Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing hexadecimal string from MAC Address

I'm trying to do some string manipulation. Is there a way to make this without a ton of if statements.

For a given MAC address I need to change the last value to +1. For example:

84:1D:A2:B9:A3:D0 => Needs to change to: 84:1D:A2:B9:A3:D1
84:1D:A2:B9:A3:99 => Needs to change to: 84:1D:A2:B9:A3:A0
84:1D:A2:B9:A3:AF => Needs to change to: 84:1D:A2:B9:A3:B0

var _cnames = "84:8D:C7:BB:A3:F0";
var res = _cnames.slice(15, 17);
if(res[1] == "0" || res[1] == "1" || res[1] == "2" || res[1] == "3"
|| res[1] == "4" || res[1] == "5" || res[1] == "6" || res[1] == "7"
|| res[1] == "8" || res[1] == "A" || res[1] == "B" || res[1] == "C"
|| res[1] == "D" || res[1] == "E"){
    res = res[0] + String.fromCharCode(res.charCodeAt(1) + 1);
}
if(res[1] == "F"){
    if(res[0] == "9"){
    res = "A0";
  }else{
        res = String.fromCharCode(res.charCodeAt(0) + 1) + "0";
  }
}
if(res[1] == "9"){
    res = res[0] + "A";
}
console.log(res);

This is my current solution but it's not as efficient as I'd like it to be. There has to be a better way to solve something like this.

like image 470
William Avatar asked Jan 26 '23 11:01

William


2 Answers

Math in non-base 10 in JS

There is a surprisingly easy answer to this. The function parseInt() accepts a second argument, the incoming value's radix. For example

parseInt("F0", 16) // Tells us that this is a base 16 (hex) number.

This will let us convert to decimal. Now the toString() method for Number types also accepts a radix for the outgoing value. So if we put it together it looks like this.

(parseInt("F0", 16) + 1 ).toString(16) // returns f1

This takes the value F0, a hex number, converts it to decimal adds the 1, and returns back a hex string.

I hope this helps!

Edit

To answer more specifically to your question, the context of a mac address is 00-FF so this below will properly pad with a leading zero, and using modulus 'wrap' any numbers over FF back down to 00 and up again.

("0"+ ((parseInt("FF", 16) + 1) % 256 ).toString(16)).substr(-2)
like image 149
John Pavek Avatar answered Jan 29 '23 12:01

John Pavek


Here is a solution (that does not handle the FF case)

It basically uses parseInt with a radix of 16 to convert to a number, and then toString with a radix of 16 to convert to hex string

var _cnames = "84:8D:C7:BB:A3:F0";

var parts = _cnames.split(':');
var last = parts.pop();
var incremented = (parseInt(last,16) + 1).toString(16).toUpperCase().padStart(2,'0');
parts.push(incremented);

var updated = parts.join(':');

console.log(updated);
like image 28
Gabriele Petrioli Avatar answered Jan 29 '23 11:01

Gabriele Petrioli