Answer» 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(); } } } 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
|