PowerShell force [int]换行(IP到长转换) [英] PowerShell force [int] to wrap (IP to Long conversion)

查看:440
本文介绍了PowerShell force [int]换行(IP到长转换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个简单的问题,因为我对PowerShell中的数学不熟悉

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

我需要在PowerShell中创建一个将IP转换为Long的转换器。它适用于较低的值,但在较高的值上它会导致整数溢出。

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

如果我输入一些低int的IP地址,就好了10.10.10.10(out 168430090)

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

但是有些情况会导致Int溢出。如果[int]达到最大值并给我一个负值,我希望PowerShell能够回滚。

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.

我作为服务台工作,我支持的软件之一需要IP格式为长格式,包括负值。

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

它是否可以在PowerShell中使用?

Is it doable in PowerShell ?

请告知您是否需要更多细节或事情尚不清楚。

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

Alex

推荐答案

一个简单的解决方案就是使用[long ]而不是[int]。

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

更新

你的评论解释了很长一段时间不是你在哪里。它听起来像你正在寻找的int。

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

我找不到让PowerShell取消选中(丢失精度)转换或算术的方法,但使用BitConverter类你可以让它工作。

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)

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

请注意,IPAddress也支持IPv6地址,但最后转换为int显然无法保存IPv6地址。

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

这篇关于PowerShell force [int]换行(IP到长转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆