PowerShell force [int] to wrap (IP to Long convers

2019-08-14 23:52发布

问题:

Just a quick question as I'm kind of new to math in PowerShell

I need to make a converter in PowerShell that converts IP to Long. It works fine for lower values, but on higher ones it is causing an Integer Overflow.

[int]$a = Read-Host "First bit of IP address"
[int]$b = Read-Host "2nd bit of IP address"
[int]$c = Read-Host "3rd bit of IP address"
[int]$d = Read-Host "4th bit of IP address"

$a *= 16777216
$b *= 65536
$c *= 256
$base10IP = $a + $b + $c + $d
Write-Host $base10IP

Works fine if I input some low-int IP address, like 10.10.10.10 (out 168430090)

But there are cases where this leads to Int overflow. I would like PowerShell to wrap around if [int] reaches maximum value and provide me a negative value.

I work as a service desk and one of the software I support needs IP in Long form, including negative values.

Is it doable in PowerShell ?

Please advise if you need more details or something is not clear.

Alex

回答1:

A simple solution would be to use [long] instead of [int].

[long]$a = Read-Host "First bit of IP address"
[long]$b = Read-Host "2nd bit of IP address"
[long]$c = Read-Host "3rd bit of IP address"
[long]$d = Read-Host "4th bit of IP address"

$a *= 16777216
$b *= 65536
$c *= 256
$base10IP = $a + $b + $c + $d
Write-Host $base10IP

And you can do what you want in even less lines of code

[IPAddress]$ip = Read-Host "IP address"
$ip.Address

UPDATE

Your comment explains a long wasn't what you where after. It sounds like an int you are looking for.

I could not find a way to have PowerShell do unchecked (losing precision) conversions or arithmetic, but using the BitConverter class you can get it working.

[byte]$a = 10
[byte]$b = 113
[byte]$c = 8
[byte]$d = 203  
[BitConverter]::ToInt32(($a, $b, $c, $d), 0)

or

[IPAddress]$ip = "10.113.8.203"
$bytes = [BitConverter]::GetBytes($ip.Address)
[BitConverter]::ToInt32($bytes, 0)

Please note that IPAddress also supports IPv6 addresses, but this last conversion to an int clearly can't hold an IPv6 address.