Categories

Powers

Many numbers in computing are based on powers of 2. I need to calculate some powers of 2 and realised that PowerShell doesn’t have  an operator for raising  a number  to a power.  In many languages ** or ^ supply this functionality.

In PowerShell we drop back to .NET and use the System.Math class (still think that should be Maths!)

[math]::Pow(2,2) raises 2 to the power 2 and gives us the answer of four.

1..30 | foreach {[math]::Pow(2,$_)}

prints out the first 30 powers of two

Just out of interest 1GB is 2 to the power 30

We can make this a bit prettier

1..30 | foreach {
"{0,3} {1,15}" -f $($_), $([math]::Pow(2,$_))
}

Check the values for 1kb, 1mb and 1gb which are

1024
1048576
1073741824

respectively.

I’ll convert this to a function and add it to the PAM maths module.

Leave a Reply