Conan1989
Conan1989

Reputation: 328

How to convert hexadecimal encoded string to hexadecimal integer

So basically what I'm trying to achieve is to get a MAC address from a text file and increment the value by one.

Been bashing my head against the Google/StackOverflow wall for a couple of hours, think there's a concept I'm just not getting.

PowerShell:

$Last_MAC_Address = (Get-Content -LiteralPath "\\UNC\Path\Last MAC Address.txt")

Write-Host ($Last_MAC_Address)
# Output: 00155DE10B73

$Next_MAC_Address = (($Last_MAC_Address | Format-Hex) + 1)

Upvotes: 5

Views: 14019

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Another option is to prefix the value with 0x and cast it to an int64:

$Next_MAC_Address = ([int64]"0x$Last_MAC_Address"+1).ToString('X12')

You could also use the format operator (-f) instead of the ToString() method:

$Next_MAC_Address = '{0:X12}' -f ([int64]"0x$Last_MAC_Address"+1)

There is, however, one thing that may be worth noting. MAC addresses aren't just random 6-byte numbers without any inner structure. They actually consist of two parts. The first 3 bytes form the Organizationally Unique Identifier (OUI), a vendor-specific prefix (00-15-5D is one of the OUIs belonging to Microsoft). Only the last 3 bytes are a random number, a unique identifier for each card from the vendor identified by the OUI.

Taking that into consideration you may want to split the MAC address accordingly, e.g. like this:

$oui, $nid = $Last_MAC_Address -split '(?<=^[0-9a-f]{6})(?=[0-9a-f]{6}$)'

or like this:

$oui = $Last_MAC_Address.Substring(0, 6)
$nid = $Last_MAC_Address.Substring(6, 6)

and increment only the NIC identifier, and only if it wouldn't overflow:

if ($nid -ne 'ffffff') {
  $Next_MAC_Address = "{0}{1:X6}" -f $oui, ([int64]"0x$nid"+1)
} else {
  Write-Error 'MAC address overflow.'
}

Upvotes: 4

Austin T French
Austin T French

Reputation: 5131

This is a 3 step process, and although PetSerAl answered it in the comments as a one liner, I'll break it down slightly for posterity (and use a different class).

The first step is to get the Hex number as a decimal (mathematical base 10, not type).

The Second step is the incrementation of the decimal.

And the final step is converting it back to hexadecimal.

broken down and not a one liner this will accomplish the task at hand:

$asDecimal = [System.Convert]::ToInt64("00155DE10B73", 16)
$asDecimal++
$asHex = [System.Convert]::ToString($asDecimal, 16)

Upvotes: 8

Related Questions