So first what is Two’s complement? Super simple simplification: It is how you can use the MSB (most significant bit) to define if the number is positive or negative. More complete and technical please read the Wikipedia article.
So why do I need this, Well in most cases you dont. But sometimes you get a int that should be unsigned but it was mangled, so you need a way to convert it to the true form. This cmdlet does that. Of course you could also just use the class System.BitConverter same way the cmdlet does.
Using the BitConverter to convert [int16] -1 to [uint16]:
PS C:\> [System.BitConverter]::TouInt16([bitconverter]::GetBytes([int16]-1),0)
65535
function Convert-IntSigned{
param
(
[Parameter(Mandatory=$true)]
[ValidateScript({@('int16','int32','int64','uint16','uint32','uint64') -contains $_.GetType().Name})]
[object]
$Integer
)
Process
{
switch ($Integer.GetType().Name)
{
'int16' {return [convert]::ToUInt16([convert]::ToString($Integer,2),2)}
'int32' {return [convert]::ToUInt32([convert]::ToString($Integer,2),2)}
'int64' {return [convert]::ToUInt64([convert]::ToString($Integer,2),2)}
'uint16' {return [convert]::ToInt16([convert]::ToString($Integer,2),2)}
'uint32' {return [convert]::ToInt32([convert]::ToString($Integer,2),2)}
'uint64' {return [convert]::ToInt64([convert]::ToString($Integer,2),2)}
}
}
}