Binary expressions
It is possible to perform operations on bit of numbers. This is specially useful for objects that are multiple of 2, as we can combine several code into a single number.
Binary operators are those most languages use:
&
| ^ ~ << >> |
binary and binary or exclusive or binary not left shiftt. Is a multiplication by 2 rigth shift. Is a division by 2 |
Numbers 1, 2, 4, 8, 16, 32... may be packed into a single number.
Example:
We assign number to various file access modes:
READ 1
WRITE 2
APPEND 4
TEXT 8
BINARY 16
We can describe the access mode of a file by a single integer number that is the addition of there flags.
To pack the previous flags, we use the binary or operator:
int mode = WRITE | TEXT | APPEND this returns the value 2 + 4 + 8, say 14.
To get one of the flag above, we use the binary and:
if (mode & WRITE) = WRITE
Examples of binary expressions : x & y keep bit common 1 in the two variables, x | y add bits 1 of each variable. |
int
x = 3 int y = 5 print x & y print x | y |
Displays: | >
3 > 5 |
Example of binary expression to extract
positives bits from a code. |
access("filename", READ) |
Displays: | > read-only mode |
It is also possible to perform binary operation on lists. This will be detailed in the chapter on arrays.
Exercises |
1) Access modes to a file are:: READ, WRITE, APPEND
and the access function is open("nom", mode). Write a call to the access function: - To write at end of a file. - To read or write at start of a file. Answer |