/// <summary> /// Try Parse /// </summary> public static bool TryParse(string value, out BigInteger result) { result = 0; return(Radix.TryToDecimal(value, out string data) && BigInteger.TryParse(data, NumberStyles.Any, CultureInfo.InvariantCulture, out result)); }
/// <summary> /// Try Parse /// </summary> public static bool TryParse(string value, out long result) { result = long.MinValue; return(Radix.TryToDecimal(value, out string data) && long.TryParse(data, NumberStyles.Any, CultureInfo.InvariantCulture, out result)); }
/// <summary> /// Converts to a string with a specific base and number of digits representation. /// </summary> public static string ToString(BigInteger value, Radix radix, int digits) { var isNegative = value < 0; string text; switch (radix) { case Radix.Dec: text = value.ToString(); if (isNegative) { text = text.Substring(1); } break; default: text = ToNbitDigitsString(value, (int)GetBitsPerDigit(radix)); break; } if (digits > 0 && text.Length < digits) { text = new string('0', digits - text.Length) + text; } return((isNegative ? "-" : "") + text); }
private void SetInteger(Radix radix, string s) { var intBase = radix == Radix.Binary ? 2 : (radix == Radix.Decimal ? 10 : 16); if (radix.IsInt(s)) { _v.IntValue = Convert.ToInt32(s, intBase); return; } if (radix.IsLong(s)) { _v.LongValue = Convert.ToInt64(s, intBase); return; } //bigint if (intBase == 10) { _v.BigIntegerValue = BigInteger.Parse(s); return; } if (intBase == 16) { _v.BigIntegerValue = BigInteger.Parse(s, NumberStyles.HexNumber); return; } //does anyone really do this? SetBigIntegerFromBinaryString(s); }
public FloatingPointFormat(Radix radix, int size, int signOffset, int signLength, int exponentOffset, int exponentLength, int mantissaOffset, int mantissaLength, string name) { Radix = radix; ByteSize = size; BitSize = size * 8; SignOffset = signOffset; SignLength = signLength; ExponentOffset = exponentOffset; ExponentLength = exponentLength; MantissaOffset = mantissaOffset; MantissaLength = mantissaLength; Name = name; // Validate arguments ThrowWhenOutOfRange(signOffset, signLength, BitSize); ThrowWhenOutOfRange(exponentOffset, exponentLength, BitSize); ThrowWhenOutOfRange(mantissaOffset, mantissaLength, BitSize); // Comute masks SignMask = new byte[size]; ComputeMask(SignMask, signOffset, signLength); ExponentMask = new byte[size]; ComputeMask(ExponentMask, exponentOffset, exponentLength); MantissaMask = new byte[size]; ComputeMask(MantissaMask, mantissaOffset, mantissaLength); }
public RealNumber(RealNumber number) { radix = number.Radix; significand = number.Significand; Exponent = number.Exponent; PrecisionBits = number.PrecisionBits; }
/// <summary> /// Calculates the required factor to convert a number from expressed in radix0 to the same /// number expressed in radix1. That is ( radix0 ^ exponent0 ) / ( radix1 ^ exponent1 ) /// </summary> private static void GetRadixChangeFactor(Radix radix0, int exponent0, Radix radix1, int exponent1, out BigInteger numerator, out BigInteger denominator) { numerator = new BigInteger(1); denominator = new BigInteger(1); var v0 = NumericHelper.GetPower(radix0, Math.Abs(exponent0)); if (exponent0 > 0) { numerator *= v0; } else { denominator *= v0; } var v1 = NumericHelper.GetPower(radix1, Math.Abs(exponent1)); if (exponent1 < 0) { numerator *= v1; } else { denominator *= v1; } }
/// <summary> /// Decode a number in required parts to be displayed. /// </summary> /// <param name="radix">Target display radix</param> /// <param name="precision">Precision bits</param> /// <param name="significand">Significand part</param> /// <param name="exponent">Exponent part</param> /// <param name="integerPart">Resulting integer part</param> /// <param name="fractionalPart">Resulting fractional part</param> /// <param name="integerDigits">Number of integer digits</param> /// <param name="fractionalDigits">Number of fractional digits</param> /// <param name="exp">Display exponent</param> public static void Decode(Radix radix, int precision, BigInteger significand, int exponent, out BigInteger integerPart, out BigInteger fractionalPart, out int integerDigits, out int fractionalDigits, out int exp) { var digits = GetRequiredDigits(significand, radix); if (exponent == 0) { integerPart = significand; fractionalPart = new BigInteger(0); integerDigits = digits; fractionalDigits = 0; exp = 0; } else { var exponentDec = exponent <= 0 ? 0 : Math.Min(exponent, precision - digits); var scientificNotation = exponent - exponentDec > 0 || exponent - exponentDec <= -precision; if (!scientificNotation && exponentDec > 0) { significand *= GetPower(radix, exponentDec); exponent -= exponentDec; digits += exponentDec; } integerDigits = scientificNotation ? 1 : exponent + digits; fractionalDigits = digits - integerDigits; exp = exponent + fractionalDigits; var decimalWeight = GetPower(radix, fractionalDigits); integerPart = BigInteger.DivRem(significand, decimalWeight, out fractionalPart); } }
public string Format(Radix fmtRadix) { var negative = Significand.Sign < 0; NumericHelper.Decode(fmtRadix, PrecisionBits, Significand, Exponent, out BigInteger integerPart, out BigInteger fractionalPart, out int integerDigits, out int fractionalDigits, out int exp); var text = negative ? "-" : "" + NumericHelper.ToString(integerPart, fmtRadix, 0); if (Exponent != 0) { text += "." + NumericHelper.ToString(fractionalPart, fmtRadix, fractionalDigits); } else if (decimalMark) { text += "."; } if (exp != 0) { text += " e" + exp.ToString(); } return(text); }
public void Store(string path) { StreamWriter sw = new StreamWriter(path); switch (Target) { case ETarget.BitCor: sw.Write("radix"); break; case ETarget.BlockMem: case ETarget.DistMem: sw.Write("memory_initialization_radix"); break; case ETarget.FIR: sw.Write("Radix"); break; default: throw new NotImplementedException(); } sw.WriteLine(" = " + Radix.ToString() + ";"); string sep = ""; switch (Target) { case ETarget.BitCor: sw.Write("pattern = "); break; case ETarget.BlockMem: sw.WriteLine("memory_initialization_vector="); sep = ","; break; case ETarget.DistMem: sw.Write("memory_initialization_vector = "); break; case ETarget.FIR: sw.Write("Coefdata= "); sep = ","; break; default: throw new NotImplementedException(); } int col = 0; foreach (object data in Data) { if (col == 8) { col = 1; sw.WriteLine(sep); } else { if (col > 0) { sw.Write(sep + " "); } col++; } sw.Write(data.ToString()); } sw.WriteLine(";"); sw.Close(); }
private static Radix BuildRadixByInserting(IEnumerable <string> strings) { var radix = new Radix(Enumerable.Empty <string>()); foreach (var s in strings) { radix.Insert(s); } return(radix); }
/// <summary> /// Calculates and trim zero digits at right from a value when expressed in a specified radix. /// </summary> public static int TrimZeroDigitsAtRight(ref BigInteger value, Radix radix, int maxCount) { var zerosAtRight = GetZeroDigitsAtRight(value, radix, maxCount); if (zerosAtRight > 0) { var divisor = GetPower(radix, zerosAtRight); value /= divisor; } return(zerosAtRight); }
private int GetTargetExponent(Radix newRadix) { if (Exponent == 0) { return(0); } var bitsPerDigit0 = NumericHelper.GetBitsPerDigit(radix); var bitsPerDigit1 = NumericHelper.GetBitsPerDigit(newRadix); var newExponent = Exponent * bitsPerDigit0 / bitsPerDigit1; return((int)Math.Round(newExponent)); }
public void TestGetTermsWithSingleCharAndMultipleBranches() { // Arrange var terms = new[] { "DARTM", "DARTF" }; var radix = new Radix(terms); var expected = terms; // Act var actual = radix.Find("D"); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Where(actual.Contains).Count()); }
public void TestRadixAddWithSingleCharStringTerm() { // Arrange var terms = new[] { "D" }; var radix = new Radix(); var expected = terms; // Act radix.Add(terms); var actual = radix.GetAllTerms(); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Where(actual.Contains).Count()); }
public void TestRadixAddWithMultipleTermsStartedWithSamePrefix() { // Arrange var terms = new[] { "DAR", "DEN" }; var radix = new Radix(); var expected = terms; // Act radix.Add(terms); var actual = radix.GetAllTerms(); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Where(actual.Contains).Count()); }
public void TestGetTermsWithFullTerm() { // Arrange var terms = new[] { "DA" }; var radix = new Radix(terms); var expected = terms; // Act var actual = radix.Find("DA"); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Where(actual.Contains).Count()); }
public static long SC() { string sc = ""; sc += showMac(); string a = FillCharacter(SystemInfo.RunQuery("Processor", "ProcessorId"), 3); string b = FillCharacter(SystemInfo.RunQuery("BaseBoard", "Product"), 3); sc += a + b; long code = 0; Radix.Decode(sc, 0x24L, ref code); return(code); }
private void SetRadix(Radix newRadix) { if (radix != newRadix) { var newExponent = GetTargetExponent(newRadix); GetRadixChangeFactor(radix, Exponent, newRadix, newExponent, out BigInteger numerator, out BigInteger denominator); significand = (significand * numerator + denominator / 2) / denominator; radix = newRadix; Exponent = newExponent; TrimNonSignificantZeros(); } }
public static char NormalizeDigit(this Radix radix, int c) { switch (radix) { case Radix.Binary: return((char)c); case Radix.Decimal: return((char)c); case Radix.Hex: return(char.ToLower((char)c)); default: throw new ArgumentOutOfRangeException(nameof(radix), radix, null); } }
/// <summary>Check if the prefix is valid for this radix type.</summary> /// <param name="radix">Radix type.</param> /// <param name="c">Char prefix.</param> /// <returns>True if this prefix valid for this radix type.</returns> public static bool IsPrefix(this Radix radix, int c) { switch (radix) { case Radix.Binary: return(c == 'b' || c == 'B'); case Radix.Decimal: return(false); case Radix.Hex: return(c == 'x' || c == 'X'); default: throw new ArgumentOutOfRangeException(nameof(radix), radix, null); } }
private static ushort TryParseUshort(string arg) { ushort result = 0; Radix radix = Radix.Decimal; switch (arg[0]) { case 'b': radix = Radix.Binary; arg = arg.Remove(0, 1); break; case 'o': radix = Radix.Octal; arg = arg.Remove(0, 1); break; case 'd': radix = Radix.Decimal; arg = arg.Remove(0, 1); break; case 'x': radix = Radix.Hexadecimal; arg = arg.Remove(0, 1); break; default: radix = Radix.Octal; break; } try { result = Convert.ToUInt16(arg, (int)radix); } catch { Console.WriteLine("{0} is not a valid 16-bit value.", arg); throw; } return(result); }
/// <summary>Check if the char is a valid digit.</summary> /// <param name="radix">Radix type.</param> /// <param name="c">Char digit.</param> /// <returns>True if the char a valid digit.</returns> public static bool IsValidDigit(this Radix radix, int c) { switch (radix) { case Radix.Binary: return(c == '0' || c == '1'); case Radix.Decimal: return(char.IsDigit((char)c)); case Radix.Hex: return((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); default: throw new ArgumentOutOfRangeException(nameof(radix), radix, null); } }
static void Main(string[] args) { int[] arreglo = Programa.ArregloLleno(); Console.WriteLine("Desordenado:"); Console.WriteLine("-----------------------------------"); foreach (int n in arreglo) { Console.Write("{0} ", n); } Radix.Sort(arreglo); Console.WriteLine("\n\nOrdenado:"); Console.WriteLine("-----------------------------------"); foreach (int n in arreglo) { Console.Write("{0} ", n); } }
/// <summary> /// Get the number of bits required for each digit of a specified radix. /// </summary> public static double GetBitsPerDigit(Radix radix) { switch (radix) { case Radix.Dec: return(3.3219281); case Radix.Bin: return(1); case Radix.Oct: return(3); case Radix.Hex: return(4); default: throw new ArgumentException(string.Format(UnableToDisplayInRadix, (int)radix)); } }
/// <summary> /// Calculate the required number of digits to display a value in a specified radix. /// </summary> public static int GetRequiredDigits(BigInteger value, Radix radix) { switch (radix) { case Radix.Dec: { var v = BigInteger.Abs(value); if (v < (int)radix) { return(1); } var digits = BigInteger.Log(v, (int)radix); return(v > 1 ? (int)Math.Ceiling(digits) : -(int)Math.Ceiling(Math.Abs(digits))); } default: return(GetDigitsCount(value, (int)GetBitsPerDigit(radix))); } }
/// <summary> /// Calculate zero digits at right when expressed in a specified radix. /// </summary> public static int GetZeroDigitsAtRight(BigInteger value, Radix radix, int maxCount) { int zerosAtRight; switch (radix) { case Radix.Dec: { var v = BigInteger.Abs(value); zerosAtRight = 0; while (maxCount == 0 || zerosAtRight < maxCount) { BigInteger.DivRem(v, 10, out BigInteger remainder); if (!remainder.IsZero) { break; } zerosAtRight++; } break; } default: { zerosAtRight = GetZeroDigitsAtRight(value, (int)GetBitsPerDigit(radix)); break; } } if (maxCount > 0 && zerosAtRight > maxCount) { zerosAtRight = maxCount; } return(zerosAtRight); }
private void SetInteger(Radix radix, string s, bool negative) { var intBase = radix == Radix.Binary ? 2 : (radix == Radix.Decimal ? 10 : 16); if (radix.IsInt(s.AsSpan())) { _v.IntValue = negative ? -Convert.ToInt32(s, intBase) : Convert.ToInt32(s, intBase); return; } if (radix.IsLong(s.AsSpan())) { _v.LongValue = negative ? -Convert.ToInt64(s, intBase) : Convert.ToInt64(s, intBase); return; } //bigint if (intBase == 10) { _v.BigIntegerValue = negative ? -BigInteger.Parse(s, CultureInfo.InvariantCulture) : BigInteger.Parse(s, CultureInfo.InvariantCulture); return; } if (intBase == 16) { _v.BigIntegerValue = negative ? -BigInteger.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture) : BigInteger.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture); return; } //does anyone really do this? SetBigIntegerFromBinaryString(s, negative); }
private static string ProcessExpression(string expression, long radix) { char[] separators = { '(', ')', '+', '-', '*', '/', '%', '\\', '^', '!' }; ArrayList processed_parts = new ArrayList(); string[] parts = expression.Split(separators, StringSplitOptions.RemoveEmptyEntries); foreach (string part in parts) { bool in_math_library = s_math_library[part.ToUpper()] != null; if (!processed_parts.Contains(part)) { // 1. consruct Math.Xxx() functions and Math.XXX constants if (in_math_library) { expression = expression.Replace(part, "Math." + s_math_library[part.ToUpper()]); } // 2. decode to base-10 else { try { expression = expression.Replace(part, Radix.Decode(part, radix).ToString()); } catch { continue; // leave part as is } } } processed_parts.Add(part); // so we don't replace it again } // Only allow small letters as constant and reserve capital letters for higher base systems // SPECIAL CASES: PI expression = expression.Replace("pi", "Math.PI"); // SPECIAL CASE: Euler's Constant expression = expression.Replace("e", "Math.E"); // SPECIAL CASE: Golden ratio expression = expression.Replace("phi", "1.61803398874989"); // SPECIAL CASE: ^ power operator parts = expression.Split('^'); // process simple case for now. if (parts.Length == 2) { double n1 = 0.0D; try { n1 = double.Parse(parts[0]); } catch { if (parts[0] == "e") { n1 = Math.E; } else if (parts[0] == "pi") { n1 = Math.PI; } else if (parts[0] == "phi") { n1 = 1.61803398874989D; } else if (parts[0] == "Math.E") { n1 = Math.E; } else if (parts[0] == "Math.PI") { n1 = Math.PI; } } double n2 = 0.0D; try { n2 = double.Parse(parts[1]); } catch { if (parts[1] == "e") { n2 = Math.E; } else if (parts[1] == "pi") { n2 = Math.PI; } else if (parts[1] == "phi") { n2 = 1.61803398874989D; } else if (parts[1] == "Math.E") { n2 = Math.E; } else if (parts[1] == "Math.PI") { n2 = Math.PI; } } expression = "Math.Pow(" + n1 + "," + n2 + ")"; } // SPECIAL CASE: ! Factorial parts = expression.Split('!'); // process simple case for now. if (parts.Length == 2) { long n = long.Parse(parts[0]); long factorial = 1L; for (long i = 1; i <= n; i++) { factorial *= i; } expression = factorial.ToString(); } // SPECIAL CASE: double and int division expression = expression.Replace("/", "/(double)"); expression = expression.Replace("\\", "/"); return(expression); }
/// <summary> /// Initializes a new instance of the <see cref="RadixStationRepository"/> class. /// </summary> /// <param name="stations">The stations.</param> public RadixStationRepository(List <string> stations) { radix = new Radix(stations); }
public ushort print(int value_, Radix base_) { throw new NotImplementedException(); }