The datatype bitsetFebruary 03. 2012
IntroductionDo you now the C function and Linux system call open? It opens a file. The exact way is specified via a list of bitwise-ored flags like O_RDONLY, O_WRONLY, O_CREAT, O_DIRECT and so on. An example would be open("hirn", O_WRONLY | O_CREAT | O_TRUNC). The values O_CREAT and so on are simply integers defined in some include-file. For simplicity Wirbel provides a special data type for those things and calls it bitset. It creates an own namespace separate from everything else - even from that of enum values. Bitset literals are prefixed with a percent sign. You can easily memorize this. Have a close look to a percent sign: Can you see the two small zeroes and the one? DeclarationsOther than enumaration values bitsets must be declared. That makes sure, that each bit in a bitset gets assigned a distinct value. Bitsets are declared using the keyword bitset: bitset sugar, milk, extrastrong Each declaration can hold up to 64 bitset atoms. Now you can be sure that %sugar, %milk and %extrastrong have distinct values. Empty bitsets are denoted with null. Bitwise operatorsBitset values can be combined using special bitset operators as known from the language C. In fact bitset is the only datatype that implements those operators in Wirbel:
Examplesbitset sugar, milk, extrastrong # declare three distinct bitset atoms a = %sugar|%milk # a contains bits %sugar and %milk b = %milk|%extrastrong # b contains bits %milk and %extrastrong c = a & b # c contains just %milk d = a | b # d contains all three bits e = a ^ b # e contains %sugar and %extrastrong f = ~%sugar # f contains %milk and %extrastrong Also the assignment operators referring to &, | and ^ are available: a = null a |= %milk a ^= %sugar a &= ~%milk # a is now %sugar The in operatorThe in operator on bitsets checks wether a set of bits is completely contained in another bitset:
if %milk|%sugar in choice:
print("Milk *and* sugar costs extra!")
return
if %milk in choice:
add_milk()
if %sugar in choice:
add_sugar()
if %extrastrong not in choice:
make_normal_strength()
Other operatorsAs with all other datatypes all relational operators ==, !=, <=, >=, <, > and is are defined for bitset values. Wirbel guarantees that all bitset atoms of the same bitset declaration are ordered and that the exact order does not change between two compile runs (in that aspect they behave different than enum values). |
| |||||||||||||||||||||||||||||||||||||||||||||||||