Skip to content

Instantly share code, notes, and snippets.

@PanosGreg
Created September 1, 2024 19:36
Show Gist options
  • Save PanosGreg/7d368a685f6ff41702ba49c695d938fb to your computer and use it in GitHub Desktop.
Save PanosGreg/7d368a685f6ff41702ba49c695d938fb to your computer and use it in GitHub Desktop.
Hex Conversions (from/to Hex)
# Convert to/from Hex
### From Byte array to Hex String
$bytes = [byte[]](10,20,30,40)
# a) via .ToString() method
$bytes.ForEach({$_.ToString('x2')}) -join ''
# b) via the string format operator
$bytes.ForEach({'{0:x2}' -f $_}) -join ''
# c) via BitConverter class
[System.BitConverter]::ToString($bytes).Replace('-',$null)
# d) via the Convert class
[System.Convert]::ToHexString($bytes)
# NOTE: this is not available on PS v5
# this is only available on PS v7+
# e) via Format-Hex
(Format-Hex -InputObject $bytes).HexBytes.Replace(' ',$null)
### From Hex to Int
$Hex = '1e'
# a) via .Parse() method from Int type
[int]::Parse($Hex,'AllowHexSpecifier')
# NOTE: the "AllowHexSpecifier", is from the enum [System.Globalization.NumberStyles]
# b) interactively on the console
0x1e
# c) via Invoke-Expression
Invoke-Expression -Command "0x$Hex"
### From Hex String to Byte Array
$Hex = '0A141E28'
# a) via Convert class
[System.Convert]::FromHexString($Hex)
# NOTE: this is not available on PS v5
# this is only available on PS v7+
# b) via .Parse() method from Int type
[regex]::Matches($Hex,'.{2}').Value | foreach {[int]::Parse($_,'AllowHexSpecifier') -as [byte]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment