Alternative Xor

I was provided with the following method:

Private Sub boldButton_Click(sender As System.Object, e As System.EventArgs) Handles boldButton.Click Dim curFont As Font Dim newFont As Font curFont = rtb.SelectionFont If curFont IsNot Nothing Then 'create the new font newFont = New Font(curFont.FontFamily, curFont.Size, curFont.Style Xor FontStyle.Bold) 'set it rtb.SelectionFont = newFont End If End Sub 

There are currently problems understanding what is happening with this piece of curFont.Style Xor FontStyle.Bold . What is an acceptable way to achieve the same result without using operator Xor ?

EDIT (As us2012 commented) Do I need an alternative?

I looked at Xor on MSDN , but still did not understand its implementation in the boldButton_Click procedure.

+4
source share
2 answers

The bitwise XOR toggles the flag. Suppose the Style bitfield looks like this:

 00000000 ^^^ BIU (Bold, Italic, Underline) 

So the value of FontStyle.Bold will be:

 00000100 

Now something Xor FontStyle.Bold simply flip this bit into something . Example:

 00000111 Xor 00000100 = 00000011 (Boldness removed) 00000001 Xor 00000100 = 00000101 (Boldness added) 

Note that the remaining bits are not affected.


Since you explicitly asked for alternatives: you can check if the style And Bold <> 0 bit is set, and then either set its style = style Or Bold or delete its style = style And (Not Bold) .

+4
source

Judging by your comment that you don’t understand what Xor is doing here, I think the explanation will help you more than the artificial alternative construction. If you want to understand how this works, you first need to know about bitwise operations. Once you know this, imagine that for a font, font styles are saved as 0s and 1s. For simplicity, suppose there are 3 bits, the first for bold, the second for italics, and the third for underscores. (So ​​101 is in bold, 011 is in italics, etc. In addition, FontStyle.Bold is 100, etc.).

Then, by analogy with bitwise operations:

oldstyle Or FontStyle.Bold creates a new style that is bold, regardless of whether the old style was. (If oldstyle was FontStyle.Italic = 010 , then 010 Or 100 = 110 , so the new style is highlighted in bold italics.)

oldstyle Xor FontStyle.Bold creates a new style that is shown in bold if the old style was not, and not bold if the old style is in bold. (Say the oldstyle was bold and italic, so 110 , then 110 Xor 100 is 010 , so italics. If, however, the old style was normal 000 , then 000 Xor 100 is 100 so it's just bold.)

+4
source

All Articles