Non-decimal radices/Input: Difference between revisions
Content added Content deleted
(Added FreeBASIC) |
No edit summary |
||
Line 802: | Line 802: | ||
Output: |
Output: |
||
<pre>123456789012345678901234567890</pre> |
<pre>123456789012345678901234567890</pre> |
||
=={{header|PowerShell}}== |
|||
'''PowerShell parses an integer prefixed with "0x" as hexadecimal. Binary and Octal conversions must use the .NET <code>[Convert]</code>. Here follows a (verbose) example:''' |
|||
<lang PowerShell> |
|||
function Select-NumberFromString |
|||
{ |
|||
[CmdletBinding(DefaultParameterSetName="Decimal")] |
|||
[OutputType([PSCustomObject])] |
|||
Param |
|||
( |
|||
[Parameter(Mandatory=$true, |
|||
ValueFromPipeline=$true, |
|||
ValueFromPipelineByPropertyName=$true, |
|||
Position=0)] |
|||
[string] |
|||
$InputObject, |
|||
[Parameter(ParameterSetName="Decimal")] |
|||
[Alias("d","Dec")] |
|||
[switch] |
|||
$Decimal, |
|||
[Parameter(ParameterSetName="Hexadecimal")] |
|||
[Alias("h","Hex")] |
|||
[switch] |
|||
$Hexadecimal, |
|||
[Parameter(ParameterSetName="Octal")] |
|||
[Alias("o","Oct")] |
|||
[switch] |
|||
$Octal, |
|||
[Parameter(ParameterSetName="Binary")] |
|||
[Alias("b","Bin")] |
|||
[switch] |
|||
$Binary |
|||
) |
|||
Begin |
|||
{ |
|||
switch ($PSCmdlet.ParameterSetName) |
|||
{ |
|||
"Decimal" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break} |
|||
"Hexadecimal" {$base = 16; $pattern = '\b[0-9A-F]+\b' ; break} |
|||
"Octal" {$base = 8; $pattern = '\b[0-7]+\b' ; break} |
|||
"Binary" {$base = 2; $pattern = '\b[01]+\b' ; break} |
|||
"Default" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break} |
|||
} |
|||
} |
|||
Process |
|||
{ |
|||
foreach ($object in $InputObject) |
|||
{ |
|||
if ($object -match $pattern) |
|||
{ |
|||
$string = $Matches[0] |
|||
} |
|||
else |
|||
{ |
|||
$string = $null |
|||
} |
|||
try |
|||
{ |
|||
$value = [Convert]::ToInt32($string, $base) |
|||
} |
|||
catch |
|||
{ |
|||
$value = $null |
|||
} |
|||
[PSCustomObject]@{ |
|||
Number = $value |
|||
String = $string |
|||
Base = $base |
|||
IsNumber = $value -is [int] |
|||
InputString = $object |
|||
} |
|||
} |
|||
} |
|||
} |
|||
</lang> |
|||
'''Using a pretend file:''' |
|||
<lang PowerShell> |
|||
$file = @' |
|||
John Doe abc1 K2hdystkrs |
|||
Jane Doe xyz2 Ew3jtdkufy |
|||
Joe Blow def3 Ouy1ttluyl |
|||
'@ -split [Environment]::NewLine |
|||
$file | Select-NumberFromString -Hexadecimal | Format-Table |
|||
</lang> |
|||
{{Out}} |
|||
<pre> |
|||
Number String Base IsNumber InputString |
|||
------ ------ ---- -------- ----------- |
|||
43969 abc1 16 True John Doe abc1 K2hdystkrs |
|||
16 False Jane Doe xyz2 Ew3jtdkufy |
|||
57075 def3 16 True Joe Blow def3 Ouy1ttluyl |
|||
</pre> |
|||
=={{Header|PureBasic}}== |
=={{Header|PureBasic}}== |