C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
We can use integers to represent arrays of boolean flags. With bitwise operators we set certain bits to zero. This saves a lot of memory. We set bits in certain positions to zero in the C# language.
Example. This program draws in GetIntBinaryString, which helps us by displaying all the bits in an integer as a string. We introduce ZeroBit, which receives the integer that stores the bits and the position of the bit we want to set to zero.
Bitwise ComplementBinary Representation
C# program that sets bits to zero using System; class Program { static void Main() { int value = 555; Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); value = ZeroBit(value, 0); Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); value = ZeroBit(value, 1); Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); value = ZeroBit(value, 3); Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); } static int ZeroBit(int value, int position) { return value & ~(1 << position); } static string GetIntBinaryString(int n) { char[] b = new char[32]; int pos = 31; int i = 0; while (i < 32) { if ((n & (1 << i)) != 0) b[pos] = '1'; else b[pos] = '0'; pos--; i++; } return new string(b); } } Output 00000000000000000000001000101011 = 555 00000000000000000000001000101010 = 554 00000000000000000000001000101000 = 552 00000000000000000000001000100000 = 544
In this example, the code for ZeroBit is at first hard to understand. It uses the constant one and shifts it by the value of the position. Then, it takes the complement of this, which creates a mask.
So: When we finally use bitwise AND on the value and the mask, we erase a one in the selected position.
Discussion. Why would you ever want to use code that sets certain bits to zero? Really the main reason is for optimization purposes. If you have a huge data structure, you can use integers to represent sets of 32 flags of 1 or zero.
Then: As you act upon this data structure, you can set certain flags to keep track of the meaning of a certain node.
Summary. It is possible to use bitwise operators in the C# language to set any bit in an integer to zero. This can enable certain complex data structures that require large amounts of memory to run efficiently.
Note: This code can be used to implement a directed acyclic word graph, as revealed on this site.