Rob
Rob

Reputation: 111

Increase / Decrease MAC Address from String in PHP

I have a mac address in string form. I am interested in taking the Mac string and increasing / decreasing it by 1 value while keeping the integrity of Hex in PHP

Ex: 00:A1:2C:3B:99:1F

-1: 00:A1:2C:3B:99:1E +1: 00:A1:2C:3B:99:20

Upvotes: 1

Views: 1358

Answers (2)

Tested

<?php
$hexval="00:A1:2C:3B:99:1F";

//First 10 MAC Address Increments
for($i=0;$i<10;$i++)
{
    $dec=hexdec($hexval);
    $dec++;
    $hexval=dechex($dec);
    $hexval=rtrim(strtoupper(chunk_split($hexval, 2, ':')),':');
    echo "00:A1:{$hexval}<br>";
}
echo "<br><br>";
//First 10 MAC Address Decrements
$hexval="00:A1:2C:3B:99:1F";
for($i=0;$i<10;$i++)
{
    $dec=hexdec($hexval);
    $dec--;
    $hexval=dechex($dec);
    $hexval=rtrim(strtoupper(chunk_split($hexval, 2, ':')),':');
    echo "00:A1:{$hexval}<br>";
}

OUTPUT :

00:A1:2C:3B:99:20
00:A1:2C:3B:99:21
00:A1:2C:3B:99:22
00:A1:2C:3B:99:23
00:A1:2C:3B:99:24
00:A1:2C:3B:99:25
00:A1:2C:3B:99:26
00:A1:2C:3B:99:27
00:A1:2C:3B:99:28
00:A1:2C:3B:99:29


00:A1:2C:3B:99:1E
00:A1:2C:3B:99:1D
00:A1:2C:3B:99:1C
00:A1:2C:3B:99:1B
00:A1:2C:3B:99:1A
00:A1:2C:3B:99:19
00:A1:2C:3B:99:18
00:A1:2C:3B:99:17
00:A1:2C:3B:99:16
00:A1:2C:3B:99:15

Upvotes: 0

DevZer0
DevZer0

Reputation: 13535

convert hex to decimal and back

$hexstring = "00:A1:2C:3B:99:1F";
$hex = preg_replace("/:/", '', $hexstring);

$dec = hexdec($hex);
$dec--; //or ++

$hex = dechex($dec);

$hexstring = implode(":", str_split($hex, 2));

Upvotes: 3

Related Questions