Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Powershell's bitwise operators

Tags:

I'm looking for example of how I would solve the scenario below:

Imagine my printer has the following property for "Status"
0 -Offline
2 -Paper Tray Empty
4 -Toner Exhausted
8 -Paper Jam

When I query status it returns a value of 12. I can obviously see that this means the printer has the Toner Exhausted and a Paper Jam, but how would I work this out with Powershell?

Thanks

like image 830
fenster Avatar asked Apr 15 '10 18:04

fenster


People also ask

Does Endianness affect bitwise operators?

Endianness only matters for layout of data in memory. As soon as data is loaded by the processor to be operated on, endianness is completely irrelevent. Shifts, bitwise operations, and so on perform as you would expect (data logically laid out as low-order bit to high) regardless of endianness.

How do you perform bitwise XOR operations?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

What is use of bitwise operators Explain with examples?

A bitwise operation operates on two-bit patterns of equal lengths by positionally matching their individual bits. For example, a logical AND (&) of each bit pair results in a 1 if both the first AND second bits are 1. If only one bit is a 1, the result is 0.


1 Answers

The boolean bitwise and operator in Powershell is -band.

Assume you define your values and descriptions in a hashtable, and have the value of 12 from the printer:

 $status = @{1 = "Offline" ; 2 = "Paper Tray Empty" ; 4 = "Toner Exhausted" ; 8 = "Paper Jam" }  $value = 12 

Then, this statement will give you the textual descriptions:

$status.Keys | where { $_ -band $value } | foreach { $status.Get_Item($_) } 

You could define the enum in Powershell, but the above works just as well, and defining enums in Powershell seems like a lot of work.

Here is an article, that talks about how to use the bitwise operators in Powershell.

like image 100
driis Avatar answered Oct 20 '22 03:10

driis