Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>By using the <code>BitArray</code> class you can write</p> <pre><code>int a = Convert.ToInt32(Console.ReadLine()); byte[] numberAsByte = new byte[] { (byte)a }; BitArray bits = new BitArray(numberAsByte); </code></pre> <p>This converts the single bits of your byte to a <code>BitArray</code>, which represents an array of Booleans that can be handled in a easy way. Note that the constructor of <code>BitArray</code> accepts an array of bytes. Since we have only one byte, we have to pass it a byte array of length 1 containing this single byte (<code>numberAsByte</code>).</p> <p>Now let us count the bits that are set.</p> <pre><code>int count = 0; for (int i = 0; i &lt; 8; i++) { if (bits[i]) { count++; } } </code></pre> <p>Note that we simply test for a bit with <code>bits[i]</code>, which yields a Boolean value. The test <code>bits[i] == true</code> as being perfectly legal and correct yields the same result but is unnecessarily complicated. The <code>if</code> statement does not require a comparison. All it wants is a Boolean value.</p> <p>This calculates an odd parity bit. </p> <pre><code>if (count % 2 == 1) { // Odd number of bits bits[7] = true; // Set the left most bit as parity bit for even parity. } </code></pre> <p>The <code>%</code> operator is the modulo operator. It yields the rest of an integer division. <code>x % 2</code> yields <code>0</code> if <code>x</code> is even. If you want an odd parity bit, you can test <code>count % 2 == 0</code> instead.</p> <p><code>BitArray</code> has a <code>CopyTo</code> method which converts our bits back to an array of bytes (containing only one byte in our case).</p> <pre><code>bits.CopyTo(numberAsByte, 0); a = numberAsByte[0]; </code></pre> <p><code>numberAsByte[0]</code> contains our number with a parity bit.</p> <hr> <p>If you want the parity bit on the right side, then you will have to shift the number to the left by one bit first.</p> <pre><code>int a = Convert.ToInt32(Console.ReadLine()); a = a &lt;&lt; 1; // Do the parity bit calculation as above and, if necessary // set the right most bit as parity bit. bits[0] = true; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload