Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Lab02_5GF_
- {
- class GF
- {
- private byte binaryPolynom;
- public GF(byte input) =>
- binaryPolynom = input;
- public byte Polynom => binaryPolynom;
- static public GF operator +(GF left, GF right) => new GF((byte)(left.Polynom ^ right.Polynom));
- static public GF operator*(GF left, GF right)
- {
- var result = default(ushort);
- for (var i = 0; i < 8; i++)
- for (var j = 0; j < 8; j++)
- result ^= (ushort)((left[i] & right[j]) << (i + j));
- return new GF((byte)DivisionRemainder(result,11));
- }
- static public ushort DivisionRemainder(ushort firstOperand, ushort secondOperand)
- {
- if (secondOperand == 0)
- throw new ArgumentException("secondOperand");
- if (firstOperand == 0)
- return 0;
- if (firstOperand == 1)
- {
- if (secondOperand == 1)
- return 0;
- return 1;
- }
- var firstOperandMaxPower = getMaxPow(firstOperand);
- var secondOperandMaxPower = getMaxPow(secondOperand);
- while (firstOperandMaxPower >= secondOperandMaxPower)
- {
- firstOperand ^= (ushort)(secondOperand << (firstOperandMaxPower - secondOperandMaxPower));
- firstOperandMaxPower = getMaxPow(firstOperand);
- }
- return firstOperand;
- }
- static public byte getMaxPow(ushort num)
- {
- var numCopy = num;
- byte pow = 0;
- while(numCopy != 1)
- {
- numCopy >>= 1;
- pow++;
- }
- return pow;
- }
- public static void modInverse(int a, int m)
- {
- int g = gcd(a, m);
- if (g != 1)
- Console.Write("Inverse doesn't exist");
- else
- {
- // If a and m are relatively
- // prime, then modulo inverse
- // is a^(m-2) mode m
- Console.Write("Modular multiplicative inverse is " +
- power(a, m - 2, m));
- }
- }
- // To compute x^y under
- // modulo m
- static int power(int x, int y, int m)
- {
- if (y == 0)
- return 1;
- int p = power(x, y / 2, m) % m;
- p = (p * p) % m;
- if (y % 2 == 0)
- return p;
- else
- return (x * p) % m;
- }
- // Function to return
- // gcd of a and b
- static int gcd(int a, int b)
- {
- if (a == 0)
- return b;
- return gcd(b % a, a);
- }
- public int this[int index] => ((1 << index) & binaryPolynom) >> index;
- public override string ToString()
- {
- var GFInStr = string.Empty;
- for (int i = 7; i >= 0; i--)
- {
- if(this[i] != 0)
- GFInStr += i == 0 ? $"1" : i > 1 ? $"x^{i}" : $"x";
- if (i != 0 && i!= 7) GFInStr += "+";
- }
- return GFInStr;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement