-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitwisePractice.cs
More file actions
102 lines (83 loc) · 2.73 KB
/
BitwisePractice.cs
File metadata and controls
102 lines (83 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
// Author: Jonathan Scholl
// Date: 9/22/2021
// Project: Practice with Bitwise https://www.youtube.com/watch?v=tNO05yKSQcU
// Description: Following AngelSix C# tutorial to learn about bitwise
*/
using System;
using System.Threading.Tasks;
namespace BitwisePractice
{
class Program
{
public enum SomeColors
{
Red = 1,
Blue = 2,
Green = 4,
Black = 8,
White = 16,
Orange = 32,
Yellow = 64,
Pink = 128,
}
static void Main(string[] args)
{
// Binary
//
// Bitwise operators
//
// And & (Both)
// Or | (Either)
// Xor ^ (Exclusive or, different)
// Not ~ (Invert)
//
//var a = 122;
//var b = 7;
//var result = (byte)(a & b);
//Console.WriteLine($"{Convert.ToString(a, 2).PadLeft(8, '0')} ~");
//Console.WriteLine($"{Convert.ToString(b, 2).PadLeft(8, '0')}");
//Console.WriteLine($"--------");
//Console.WriteLine($"{Convert.ToString(result, 2).PadLeft(8, '0')}");
//Console.WriteLine($"--------\n");
//
// Bitwise operators
//
// And & (Both)
// Or | (Either)
// Xor ^ (Exclusive or, different)
// Not ~ (Invert)
//
//byte c = 25;
// var cResult = (byte)(c << 1);
// Console.WriteLine($"{Convert.ToString(c, 2).PadLeft(8, '0')} << 1");
//Console.WriteLine($"--------");
//Console.WriteLine($"{Convert.ToString(cResult, 2).PadLeft(8, '0')}");
// Usage
//
// Toggling boolean
// Enum flags
// Masking
//
// Invert booleans
var d = true;
d ^= true;
// Enum flags
var someColors = (byte)(SomeColors.Blue);
Console.WriteLine($"{Convert.ToString((byte)someColors, 2).PadLeft(8, '0')}");
if ((someColors & (byte)SomeColors.Blue) == (byte)SomeColors.Blue)
{
Console.WriteLine("Blue was included");
}
if ((someColors & (byte)SomeColors.White) == (byte)SomeColors.White)
{
Console.WriteLine("White was included");
}
// Masking
var input = (byte)(SomeColors.White | SomeColors.Blue);
var mask = (byte)SomeColors.Blue;
var r = input & mask;
Console.ReadLine();
}
}
}