Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitmask conversion in Powershell

I'm working with a bitmask that represents error codes. For example, a value of 3 (binary 11) indicates that errors 1 and 2 were encountered (binary 1 and 10). I'm looking for a function that converts this to an array automatically in powershell.

I've looked around the internet and couldn't find anything particular to this scenario. I've written a function that does this, but it's not very readable if the user isn't familiar with bitmasks.

EDIT To be specific, I'm looking for a function that takes 'raw' error bits and uses that to return an array of errors. For example:

GetErrorList 3779

returns an array containing:

1, 2, 64, 128, 512, 1024, 2048

like image 308
Speerian Avatar asked Sep 01 '25 01:09

Speerian


2 Answers

Set up a hashtable with translations for each bit and use the binary AND operator (-band) to find out what errors have been raised:

function Get-ErrorDescription {

    param([int]$ErrorBits)

    $ErrorTable = @{
        0x01 = "Error1"
        0x02 = "Error2"
        0x04 = "Error3"
        0x08 = "Error4"
        0x10 = "Error5"
        0x20 = "Error6"
    }

    foreach($ErrorCode in $ErrorTable.Keys | Sort-Object){
        if($ErrorBits -band $ErrorCode){
            $ErrorTable[$ErrorCode]
        }
    }
}

returns a string array of errors found, or $null

PS C:\> Get-ErrorDescription -ErrorBits 3
Error1
Error2
like image 167
Mathias R. Jessen Avatar answered Sep 02 '25 16:09

Mathias R. Jessen


EDIT: I found a really cool way to do this with enum flags in Powershell 5:

[flags()] Enum ErrorTable
{
  Error1 = 0x01
  Error2 = 0x02
  Error3 = 0x04
  Error4 = 0x08
  Error5 = 0x10
  Error6 = 0x20
}

PS C:\> $errorcodes = [ErrorTable]'Error1,Error2'
PS C:\> $errorcodes
Error1, Error2
PS C:\> $errorcodes = [ErrorTable]3
PS C:\> $errorcodes
Error1, Error2
like image 24
js2010 Avatar answered Sep 02 '25 16:09

js2010