Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: How to add parity bits to binary numbers c#  (Read 8865 times)

0 Members and 1 Guest are viewing this topic.

Ashar346

    Topic Starter


    Newbie
    • Experience: Beginner
    • OS: Unknown
    How to add parity bits to binary numbers c#
    « on: February 07, 2012, 11:45:37 AM »
    Hello. This is my code. I am trying to make a program on c# which the user types in a 7-bit binary number and the program prints the number with an even parity bit added to it on the left. It says some things don't fit in the context. Is there any way you could do a code as I think it is wrong.


    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Linq;
    using System.Text;

    namespace something
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Please enter a 7-bit binary number:");
                int number = Convert.ToInt32(Console.ReadLine());
                byte[] numberAsByte = new byte[] { (byte)number };

                byte bitsSet=0;

                for (int i = 0; i >= 0; i--)
                {
               
                    if ((number & (1 << i)) > 0)
                    {
                        bitsSet++;
                    }

                }
                if (bitsSet % 2 == 1)
                {
                    bits[7] = true;
                }
                Array.CopyTo(numberAsByte, 0, out bits);
                number = numberAsByte[0];
                Console.WriteLine("The binary number with a parity bit is:");
                Console.WriteLine(number);
                Console.ReadLine();
            }
           
        }
    }

    bwilcutt



      Greenhorn

      • Curious Internet
    • Certifications: List
    • Experience: Guru
    • OS: Unknown
    Re: How to add parity bits to binary numbers c#
    « Reply #1 on: February 16, 2012, 03:58:27 PM »
    Parity works by setting the high bit to 1 when there are an even number of bits in the number, and 0 if there are odd bits.

    int c = 0;

    for (int i = 0; i < sizeof(byte) - 1; i++)  // Minus 1 because we don't care about high bit
    {
        if (mybyte & (1 << i))
         c++;  /* cheap shot at C#, sorry :-) */
    }

    if (c & 0x01)
       mybyte |= 0x80;  // Even parity
    else
       mybyte &= 0x7f;  // Odd parity

    This is just psuedo code, of course, but should clear up your approach.

    Bryan Wilcutt
    Dr. Bryan Wilcutt, DC.S.