What did these characters mean (& ~ |) when using the font class

I have the following code

Font oldf;
Font newf;

oldf = this.richText.SelectionFont;

if (oldf.Bold)
  newf = new Font(oldf, oldf.Style & ~FontStyle.Bold);
else
  newf = new Font(oldf, oldf.Style | FontStyle.Bold);

I know this code, but I do not know what it meant these characters &, | and ~.
(or, or, not), or am I mistaken?

+3
source share
7 answers

Like others, they are bitwise operators. FontStyleis a bit field (a set of flags).


oldf.Style & ~FontStyle.Bold

It means β€œremove the bold”, but looking at the basic math, you get something like this.

(a) FontStyle.Bold  = 0b00000010;  // just a guess, it doesn't really matter
(b) oldf.Style      = 0b11100111;  // random mix here
// we want Bold "unset"
(c) ~FontStyle.Bold = 0b11111101;
=> (b) & (c)        = 0b11100101;  // oldf without Bold

new Font(oldf, oldf.Style | FontStyle.Bold)

This means that we want to highlight the Bold font. By OR'ing with the existing value (this also means that what is already in bold will remain in bold).

(a) FontStyle.Bold  = 0b00000010;  // just a guess, it doesn't really matter
(b) oldf.Style      = 0b11100000;  // random mix here
=> (b) | (c)        = 0b11100010;  // oldf with Bold
+1
source

. | OR & AND, ~ .

, (Style, Bold ..) , . , , . -, - , OR-ed, "".

Style, true AND, NOT Bold.

Style Bold.

+1

, .

new Font(oldf, oldf.Style & ~FontStyle.Bold);

( , , -, , ).

new Font(oldf, oldf.Style | FontStyle.Bold);

ORing enum .

, , , , .

0

.

:

newf = new Font(oldf, oldf.Style & ~FontStyle.Bold);

, EXCEPT ( ) .

:

newf = new Font(oldf, oldf.Style | FontStyle.Bold);

, FontStyle.Bold.

0

: http://msdn.microsoft.com/en-us/library/6a71f45d%28v=vs.71%29.aspx ( " ( )" )

, . , | OR, ~ . :

00000001b & 00000011b == 00000001b (any bits contained by both bytes)
00000001b | 00001000b == 00001001b (any bits contained in either byte)
~00000001b == 11111110b (toggle all bits)

, .

0
source

Variables are enumerations of the bit flag. Thus, you can and them together with the bitwise operator AND "$" or OR together with the bitwise operator OR "|".

They are used with an enumeration, so you can specify a few examples of options below.

[Flags]
enum Numbers {
  one = 1   // 001
  two = 2   // 010
  three = 4 // 100
}   

var holder = Numbers.two | Numbers.one; //one | two == 011

if ((holder & Numbers.one) == Numbers.one) {
  //Hit
}

if ((holder & Numbers.two) == Numbers.two) {
  //Hit
}

if ((holder & Numbers.three) == Numbers.three) {
  //Not hit in this example
}
0
source

All Articles