Skip to content

Instantly share code, notes, and snippets.

@drlsdee
Created April 4, 2023 13:26
Show Gist options
  • Save drlsdee/c3fc67c30174879b33bf984755e30610 to your computer and use it in GitHub Desktop.
Save drlsdee/c3fc67c30174879b33bf984755e30610 to your computer and use it in GitHub Desktop.
Two functions to convert software versions from System.Version to hex string and back
$Script:styles = [System.Globalization.NumberStyles]::AllowHexSpecifier
$Script:formats = [cultureinfo]::InvariantCulture
function ConvertTo-CppHexVersion {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[Alias('Version')]
[version]
$InputObject
)
begin {
[string]$formatHexStr = '{0:x2}'
[string]$formatOutput = '0x{0}'
[string[]]$versionParts = 'Major','Minor','Build','Revision'
}
process {
[string[]]$versionSubstr = $versionParts.ForEach({
[int]$versionPart = $InputObject.$_
if ($versionPart -lt 0) { $versionPart = 0 }
[string]::Format($formatHexStr,$versionPart)
})
[string]$versionConcat = [string]::Concat($versionSubstr)
[string]$outputObject = [string]::Format($formatOutput,$versionConcat)
return $outputObject
}
}
function ConvertFrom-CppHexVersion {
[CmdletBinding()]
[OutputType([version])]
param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[Alias('Version')]
[ValidateScript({
[ref]$refInt32 = 0
[bool]$isInt32 = [int]::TryParse('01020304',$Script:styles,$Script:formats,$refInt32)
return $isInt32
})]
[string]
$InputObject
)
begin {
$PartSize = 2
}
process {
# Remove hex specifier if present
[string]$stringToProcess = $InputObject -replace '^0x'
if ([string]::IsNullOrEmpty($stringToProcess)) { return }
# Split by parts
[char[]]$charArray = $stringToProcess.ToCharArray()
[int[]]$versionParts = for ($index = 0; $index -lt $charArray.Count; $index += $PartSize) {
[int]$arrayTail = $charArray.Count - $index
[int]$buffSize = [System.Math]::Min($arrayTail,$PartSize)
[char[]]$buffer = [char[]]::new($buffSize)
[array]::Copy($charArray,$index,$buffer,0,$buffSize)
[int]::Parse([string]::new($buffer),$Script:styles)
}
if ($versionParts.Count -gt 6) { return }
[string]$versionJoin = [string]::Join('.',$versionParts)
[version]$outputObject = [version]::new($versionJoin)
return $outputObject
}
}
<#
'0x01040000','0x01060000','0x000b0500','0x01030000','0x00090000' | ConvertFrom-CppHexVersion
'0.9.1' | ConvertTo-CppHexVersion
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment