Monday, June 11, 2012

Converting Letters to Numbers and Bit Masks


Sometimes, you may need to turn characters such as drive letters into numbers or even bit masks. With a little bit of math, this is easily doable. Here is a sample:

Let's start with a dirty and unsorted list of drive letters. This is how PowerShell can sort and normalize them:
$DriveList = 'a''b:''d''Z''x:'
$DriveList |
    
ForEach-Object { $_.toUpper()[0] } |
     Sort-Object
With a little more code, you get back drive indices, taking advantage of the ASCII code of characters:
$driveList = 'a''b:''d''Z''x:'
$DriveList |
    
ForEach-Object { $_.toUpper()[0] } |
    
Sort-Object |
    ForEach-Object { ([Byte]$_-65 }
To turn this into a bit mask, use the Pow() function:
$driveList = 'a''b:''d''Z''x:'

$DriveList |
    
ForEach-Object { $_.toUpper()[0] } |
    
Sort-Object |
    
ForEach-Object { [Math]::Pow(2,(([Byte]$_-65)) }