PoshCode Archive  Artifact [286c912b24]

Artifact 286c912b24da26ef3128c06ea3b6f70af8cae97cddc91eb35df06faadbb65df2:

  • File PoSh-hex2dec.ps1 — part of check-in [477399ce5b] at 2018-06-10 13:43:34 on branch trunk — Fixed some issues (user: greg zakharov size: 1753)

# encoding: ascii
# api: powershell
# title: PoSh hex2dec
# description: Fixed some issues
# version: 0.1
# type: function
# author: greg zakharov
# license: CC0
# function: Convert-Hex2Dec
# x-poshcode-id: 4600
# x-archived: 2013-11-14T15:07:25
# x-published: 2013-11-11T14:12:00
#
#
#requires -version 2.0
Set-Alias hex2dec Convert-Hex2Dec

function Convert-Hex2Dec {
  <#
    .EXAMPLE
        PS C:\> Convert-Hex2Dec 7717
        7717 = 0x1E25
    .EXAMPLE
        PS C:\> hex2dec fa
        0xFA = 250
    .EXAMPLE
        PS C:\> "0x15" | hex2dec
        0x15 = 21
    .EXAMPLE
        PS C:\> Convert-Hex2Dec x200
        0x200 = 512
  #>
  param(
    [Parameter(Mandatory=$true,
               ValueFromPipeline=$true)]
    [ValidateNotNullOrEmpty()]
    [String]$Number
  )

  begin {
    function col($c) {$host.UI.RawUI.ForegroundColor = $c}
    $old = $host.UI.RawUI.ForegroundColor
  } 
  process {
    if ($Number -match "^[0-9]+$") {
      col "Magenta"
      "{0} = 0x{1:X}`n" -f $Number, [Int32]$Number
      col $old
    }
    elseif ($Number -match "^(0x|x)|([0-9]|[a-f])+$") {
      col "Cyan"
      try {
        switch ($Number.Substring(0, 1)) {
          "x" {"0x{0} = {1}`n" -f $Number.Substring(1, $Number.Length - 1).ToUpper(), `
                                                                [Int32]("0" + $Number)}
          "0" {"0x{0} = {1}`n" -f $Number.Substring(2, $Number.Length - 2).ToUpper(), `
                                                                        [Int32]$Number}
          default {
            "0x{0} = {1}`n" -f $Number.ToUpper(), [Int32]("0x" + $Number)
          }
        }
      }
      catch {}
      col $old
    }
  }
}