/// <summary> /// Converts from decimal to arbitrary base <see cref="Number"/>. /// </summary> /// <param name="decimalValue"> The value that is converted</param> /// <param name="resultBase"> The base of the result of conversion</param> /// <returns><see cref="Number"/></returns> public BaseRepresentation ToBase(string inputStr, int inputBase, int resultBase) { if (IsValidRadix(inputBase) && IsValidRadix(resultBase)) { if (IsValidString(inputStr, inputBase)) { string integerStr, fractionalStr; double fractionalPart, decimalValue, integerPart; BaseRepresentation inputInDecimal; // First, convert the input Number to Decimal if (IsFloatingPointStr(inputStr)) { // Split the whole value into integer part and fraction part strings string[] valueParts = inputStr.Split('.'); integerStr = valueParts[0]; fractionalStr = valueParts[1]; // Convert each part integerPart = ArbitraryBaseToDecimal(integerStr, inputBase); fractionalPart = ArbitraryFractionToDecimal(fractionalStr, inputBase); // Make the fractionalPart negative if the integer part is also negative // This is needed when both parts are added together to create whole value if (integerPart < 0) { fractionalPart *= -1; } decimalValue = (double)integerPart + fractionalPart; inputInDecimal = new BaseRepresentation(10, decimalValue, decimalValue.ToString(), comp.GetComplement(decimalValue.ToString(), resultBase)); } else { // Not a floating point number, convert only the integer part. integerPart = ArbitraryBaseToDecimal(inputStr, inputBase); inputInDecimal = new BaseRepresentation(10, integerPart, integerPart.ToString(), comp.GetComplement(integerPart.ToString(), resultBase)); } if (resultBase == 10) { return(inputInDecimal); } else { // Convert to result Base return(ToBase(inputInDecimal, resultBase)); } } else { throw new ArgumentException("Input Str is invalid"); } } else { throw new ArgumentException("Radix is invalid"); } }
/// <summary> /// Converts from decimal to arbitrary base <see cref="Number"/>. /// </summary> /// <param name="number"> The value that is converted.</param> /// <param name="resultBase"> The base of the result of conversion.</param> /// <returns>The<see cref="Number"/> in given base</returns> public BaseRepresentation ToBase(BaseRepresentation number, int resultBase) { return(ToBase(number.DecimalValue, resultBase)); }