示例#1
0
        decimal ProcessPostfix(Queue <Token> postfix)
        {
            Stack <Token> stack = new Stack <Token>();
            Token         token = null;

            while (postfix.Count > 0)
            {
                token = postfix.Dequeue();
                if (token is NumberBase)
                {
                    stack.Push(token);
                }
                else if (token is OperatorBase)
                {
                    NumberBase right = (NumberBase)stack.Pop();
                    NumberBase left  = (NumberBase)stack.Pop();
                    decimal    value = ((OperatorBase)token).Calculate(left.Value, right.Value);
                    stack.Push(new Number(value));
                }
                else if (token is FunctionBase)
                {
                    NumberBase arg   = (NumberBase)stack.Pop();
                    decimal    value = ((FunctionBase)token).Calculate(arg.Value);
                    stack.Push(new Number(value));
                }
            }
            decimal toret = ((NumberBase)stack.Pop()).Value;

            if (stack.Count != 0)
            {
                throw new ArgumentException(InvalidMessage);
            }
            return(toret);
        }
        private void UpdateFromCurrentTextBox()
        {
            Options options = this.PackageOptions;

            if (options != null)
            {
                NumberBase    numBase = (NumberBase)this.currentTextBox.Tag;
                BaseConverter num     = new BaseConverter(this.currentTextBox.Text, options, numBase, this.CurrentByteOrder, this.CurrentNumberType);

                // Update the display.
                bool previouslyUpdatingDisplay = this.updatingDisplay;
                this.updatingDisplay = true;
                try
                {
                    if (this.hexEdit != this.currentTextBox)
                    {
                        this.hexEdit.Text = num.HexValue;
                    }

                    if (this.decimalEdit != this.currentTextBox)
                    {
                        this.decimalEdit.Text = num.DecimalValue;
                    }

                    if (this.binaryEdit != this.currentTextBox)
                    {
                        this.binaryEdit.Text = num.BinaryValue;
                    }
                }
                finally
                {
                    this.updatingDisplay = previouslyUpdatingDisplay;
                }
            }
        }
        internal void SetRadixButton(NumberBase numberBase)
        {
            switch (numberBase)
            {
            case NumberBase.DecBase:
                DecimalButton.IsChecked = true;
                break;

            case NumberBase.HexBase:
                HexButton.IsChecked = true;
                break;

            case NumberBase.OctBase:
                OctButton.IsChecked = true;
                break;

            case NumberBase.BinBase:
                BinaryButton.IsChecked = true;
                break;

            default:
                Debug.Assert(false);
                break;
            }
        }
示例#4
0
        private void OnCurrentRadixTypePropertyChanged(NumberBase oldValue, NumberBase newValue)
        {
            Num0Button.IsEnabled = true;
            Num1Button.IsEnabled = true;
            Num2Button.IsEnabled = true;
            Num3Button.IsEnabled = true;
            Num4Button.IsEnabled = true;
            Num5Button.IsEnabled = true;
            Num6Button.IsEnabled = true;
            Num7Button.IsEnabled = true;
            Num8Button.IsEnabled = true;
            Num9Button.IsEnabled = true;

            if (newValue == NumberBase.BinBase)
            {
                Num2Button.IsEnabled = false;
                Num3Button.IsEnabled = false;
                Num4Button.IsEnabled = false;
                Num5Button.IsEnabled = false;
                Num6Button.IsEnabled = false;
                Num7Button.IsEnabled = false;
                Num8Button.IsEnabled = false;
                Num9Button.IsEnabled = false;
            }
            else if (newValue == NumberBase.OctBase)
            {
                Num8Button.IsEnabled = false;
                Num9Button.IsEnabled = false;
            }
        }
示例#5
0
        public static string NumberToBaseString(int v, NumberBase noBase, int d = -1, bool showPrefix = false)
        {
            int digits = d < 0 ? (int)noBase : d;

            switch (noBase)
            {
            case NumberBase.Decimal:
                if (digits == 0)
                {
                    return(v.ToString("D"));
                }
                return(v.ToString("D" + digits));

            case NumberBase.Hexadecimal:
                if (digits == 0)
                {
                    return(v.ToString("X"));
                }
                return((showPrefix ? "$" : "") + v.ToString("X" + digits));

            case NumberBase.Binary:
                string b = "";
                int    i = 0;
                while (digits == 0 ? v > 0 : i < digits)
                {
                    b  += (v & 1);
                    v >>= 1;
                    i++;
                }
                return((showPrefix ? "%" : "") + b);
            }
            return("");
        }
示例#6
0
        private static bool TryParse(string byteString, NumberBase numBase, out byte byteValue)
        {
            bool result;

            if (numBase == NumberBase.Hex)
            {
                result = byte.TryParse(byteString, NumberStyles.HexNumber, null, out byteValue);
            }
            else
            {
                result    = true;
                byteValue = 0;
                const int UpperBound = BitsPerByte - 1;
                for (int i = UpperBound; i >= 0; i--)
                {
                    char ch = byteString[UpperBound - i];
                    if (ch == '1')
                    {
                        byteValue |= (byte)(1 << i);
                    }
                    else if (ch != '0')
                    {
                        result = false;
                        break;
                    }
                }
            }

            return(result);
        }
示例#7
0
 public static string ToString(this BigInteger value, NumberBase numberBase)
 {
     return(numberBase switch
     {
         NumberBase.BIN => value.ToBinaryString(),
         NumberBase.HEX => value.ToHexadecimalString(),
         _ => value.ToString(),
     });
示例#8
0
        private static int CalculateDigitsLength(BigInteger value, NumberBase @base)
        {
            if (@base == NumberBase.DEC && value > 0)
            {
                return((int)Math.Floor(BigInteger.Log10(value) + 1));
            }

            return(value.ToString(@base).Length);
        }
示例#9
0
 public static string ConvertFromBaseToBase(string numberString, NumberBase fromNumberBase, NumberBase toNumberBase)
 {
     try
     {
         return(Convert.ToString(Convert.ToInt64(numberString, (int)fromNumberBase), (int)toNumberBase));
     }
     catch (Exception)
     {
         throw new OverflowException("Number is too big. Max 64 bit is allowed");
     }
 }
示例#10
0
        public void MatchNumber_NIPNumber_RemoveDashInNumber()
        {
            IList <IMatchNumber> numbersType = new List <IMatchNumber>();

            numbersType.Add(new MatchNIPNumber());
            numbersType.Add(new MatchRegonNumber());

            MatchFactory match = MakeMatchClass();

            NumberBase number = match.MatchNumber(numbersType, "683-432-23-13");

            Assert.IsInstanceOf(typeof(NIPNumber), number);
        }
示例#11
0
        public void MatchNumber_ReturnInstanceOfRegonClass()
        {
            IList <IMatchNumber> numbersType = new List <IMatchNumber>();

            numbersType.Add(new MatchRegonNumber());
            numbersType.Add(new MatchNIPNumber());

            MatchFactory match = MakeMatchClass();

            NumberBase number = match.MatchNumber(numbersType, "432522830");

            Assert.IsInstanceOf(typeof(RegonNumber), number);
        }
示例#12
0
        public void MatchNumber_NIPNumber_UEFormatNumber()
        {
            IList <IMatchNumber> numbersType = new List <IMatchNumber>();

            numbersType.Add(new MatchNIPNumber());
            numbersType.Add(new MatchRegonNumber());

            MatchFactory match = MakeMatchClass();

            NumberBase number = match.MatchNumber(numbersType, "PL6834322313");

            Assert.IsInstanceOf(typeof(NIPNumber), number);
        }
示例#13
0
        public void MatchNumber_InValidNumber_ReturnNull()
        {
            IList <IMatchNumber> numbersType = new List <IMatchNumber>();

            numbersType.Add(new MatchNIPNumber());
            numbersType.Add(new MatchRegonNumber());

            MatchFactory match = MakeMatchClass();

            NumberBase number = match.MatchNumber(numbersType, "683432");

            Assert.AreSame(null, number);
        }
        public static string ToString(this int value, NumberBase numberBase, int?width = null)
        {
            switch (numberBase)
            {
            case NumberBase.Binary:
                return(value.ToBinary(width));

            case NumberBase.Decimal:
                return(value.ToString());

            default:
                return(value.ToString());
            }
        }
示例#15
0
            public double Calculate(string input)
            {
                if (input == null)
                {
                    throw new ArgumentNullException("input");
                }
                if (input == string.Empty)
                {
                    throw new ArgumentException(InvalidMessage);
                }
                string        expression = FormatExpression(input);
                TokenFactory  tf         = new TokenFactory();
                Queue <Token> postfix    = GetPostFix(expression, tf);

                if (nopwaswritten == false)
                {
                    nopwaswritten = true;
                    Queue <Token> helper = GetPostFix(expression, tf);
                    while (helper.Count > 0)
                    {
                        Token tokenholder = helper.Dequeue();
                        if (tokenholder is NumberBase)
                        {
                            if (Convert.ToString(tokenholder) == "ONP_lvl_hard.Program+Interpreter+variable")
                            {
                                resultofONP = resultofONP + tokenholder + ' ';
                            }
                            else
                            {
                                NumberBase valueholder = (NumberBase)tokenholder;
                                resultofONP = resultofONP + valueholder.Value + ' ';
                            }
                        }
                        else
                        {
                            if (helper.Count != 0)
                            {
                                resultofONP = resultofONP + tokenholder + ' ';
                            }
                            else
                            {
                                resultofONP = resultofONP + tokenholder;
                            }
                        }
                    }
                    ONPwriter(resultofONP);
                }

                return(ProcessPostfix(postfix));
            }
示例#16
0
        public IDataContent <Company> GetData()
        {
            IDataContent <Company> dataContent = new CompanyContent();

            dataContent.Headers = Headers;

            MatchFactory factory = new MatchFactory();

            NumberBase concreteNumberType = factory.MatchNumber(NumbersToCheck, Number);

            if (concreteNumberType != null && concreteNumberType.IsValid(Number))
            {
                try
                {
                    Number = concreteNumberType.FormatNumber(Number);
                    ISession session = NHibernateManager.BeginSessionTransaction();
                    dataContent.Data = CompanyDAO.Instance.GetCompanyDataByNumber(Number, session);
                    NHibernateManager.CloseSessionTransaction();
                    dataContent.Status = StatusEnum.Valid.ToString();
                    if (dataContent.Data == null)
                    {
                        dataContent.Message = "Brak danych";
                        dataContent.Status  = StatusEnum.Error.ToString();
                    }
                }
                catch (Exception e)
                {
                    NHibernateManager.CloseSessionTransaction();
                    throw new Exception(e.Message);
                }
            }
            else
            {
                dataContent.Message = "Podany numer jest niepoprawny";
                dataContent.Status  = StatusEnum.Error.ToString();
            }
            LogManager log = new LogManager();

            log.LogData(dataContent);

            return(dataContent);
        }
示例#17
0
        public BaseConverter(string textValue, Options options, NumberBase numBase, NumberByteOrder byteOrder, NumberType numberType)
        {
            this.options = options;

            if (!string.IsNullOrEmpty(textValue))
            {
                switch (numBase)
                {
                case NumberBase.Binary:
                    this.InitializeFromBinary(textValue, byteOrder, numberType);
                    break;

                case NumberBase.Decimal:
                    this.InitializeFromDecimal(textValue, byteOrder, numberType);
                    break;

                case NumberBase.Hex:
                    this.InitializeFromHex(textValue, byteOrder, numberType);
                    break;
                }
            }
        }
示例#18
0
        public static string NumberToBaseString(int v, NumberBase noBase, int d = -1, bool showPrefix = false)
        {
            var digits = d < 0 ? (int)noBase : d;

            switch (noBase)
            {
            case NumberBase.Decimal:
                return(Convert.ToString(v).PadLeft(digits, '0'));

            case NumberBase.Hexadecimal:
            case NumberBase.Color:
                if (noBase == NumberBase.Color)
                {
                    Color color = ColorRGB555(v);
                    return($"rgb555({color.R},{color.G},{color.B})");
                }
                return((showPrefix ? "$" : "") + Convert.ToString(v, 16).PadLeft(digits, '0').ToUpper());

            case NumberBase.Binary:
                return((showPrefix ? "%" : "") + Convert.ToString(v, 2).PadLeft(digits, '0'));
            }
            return("");
        }
示例#19
0
 public void HexFormat()
 {
     numberBase = NumberBase.Hexadecimal;
 }
示例#20
0
 public void DecFormat()
 {
     numberBase = NumberBase.Decimal;
 }
 public static bool TryNumberBase(string value, out NumberBase numberBase) => numberBaseDict.TryGetValue(value, out numberBase);
示例#22
0
        private static Tuple <string, NumberBase> SplitNumericLiteral(string text)
        {
            // Remove digit separators first so we can shrink the text correctly (e.g., trim leading zeros).
            text = text.Replace("_", string.Empty);

            // Skip numeric suffixes including compound ones like UL and LU.
            int substringLength = text.Length;

            while (substringLength >= 1 && CSharpNumericSuffixes.Contains(text[substringLength - 1]))
            {
                substringLength--;
            }

            // Skip a fractional zero, which can be used to make a double without using a suffix.
            const string FractionalZero = ".0";

            if (substringLength > FractionalZero.Length &&
                string.CompareOrdinal(text, substringLength - FractionalZero.Length, FractionalZero, 0, FractionalZero.Length) == 0)
            {
                substringLength -= FractionalZero.Length;
            }

            // Skip hex or binary specifiers.  This allows 0x1 or 0b1 to match 1, for example.
            int          startIndex   = 0;
            const string HexPrefix    = "0x";
            const string BinaryPrefix = "0b";
            NumberBase   numberBase   = NumberBase.Decimal;

            if (text.StartsWith(HexPrefix, StringComparison.OrdinalIgnoreCase))
            {
                startIndex      += HexPrefix.Length;
                substringLength -= HexPrefix.Length;
                numberBase       = NumberBase.Hexadecimal;
            }
            else if (text.StartsWith(BinaryPrefix, StringComparison.OrdinalIgnoreCase))
            {
                startIndex      += BinaryPrefix.Length;
                substringLength -= BinaryPrefix.Length;
                numberBase       = NumberBase.Binary;
            }

            // Skip leading zeros but not the final zero.  This allows 00 to match 0, for example.
            while (startIndex < text.Length && substringLength > 1 && text[startIndex] == '0')
            {
                startIndex++;
                substringLength--;
            }

            string result;

            if ((startIndex + substringLength) <= text.Length && (startIndex > 0 || substringLength < text.Length))
            {
                result = text.Substring(startIndex, substringLength);
            }
            else
            {
                result = text;
            }

            return(Tuple.Create(result, numberBase));
        }
示例#23
0
 private void PrintColored(BigInteger value, NumberBase @base, int pad = 0, ConsoleColor valueColor = ConsoleColor.Gray)
 {
     _console.Output.WithForegroundColor(valueColor, (output) => output.Write(value.ToString(@base).PadLeft(pad)));
 }
示例#24
0
        private static byte[] GetMachineBytesFromText(string textValue, NumberByteOrder byteOrder, NumberBase numBase, int requiredNumBytes)
        {
            Debug.Assert(numBase == NumberBase.Binary || numBase == NumberBase.Hex, "GetMachineBytesFromText is only for binary and hex values.");

            byte[] result      = null;
            bool   validLength = ValidateAndNormalizeByteText(ref textValue, byteOrder, numBase, requiredNumBytes);

            if (validLength)
            {
                bool        valid       = true;
                string[]    byteStrings = SplitIntoByteStrings(textValue, numBase == NumberBase.Binary ? BitsPerByte : 2);
                List <byte> byteList    = new List <byte>(requiredNumBytes);
                foreach (string byteString in byteStrings)
                {
                    if (TryParse(byteString, numBase, out byte byteValue))
                    {
                        byteList.Add(byteValue);
                    }
                    else
                    {
                        valid = false;
                        break;
                    }
                }

                if (valid)
                {
                    result = byteList.ToArray();

                    // Regardless of input byte order we must return bytes that match machine byte order
                    // (i.e., BitConverter.IsLittleEndian) because our output will be passed to BitConverter.
                    result = EnsureRequestedByteOrder(result, byteOrder);
                }
            }

            return(result);
        }
示例#25
0
 public Number(BigInteger value, NumberBase @base)
 {
     Value = value;
     Base  = @base;
 }
示例#26
0
        private static bool ValidateAndNormalizeByteText(ref string textValue, NumberByteOrder byteOrder, NumberBase numBase, int numRequiredBytes)
        {
            // Ignore whitespace (leading, trailing, and between digit groups) and non-printable control characters.
            textValue = new string(textValue.Where(ch => !char.IsWhiteSpace(ch) && !char.IsControl(ch)).ToArray());

            // Ignore 0x prefix for hex
            if (numBase == NumberBase.Hex && textValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                textValue = textValue.Substring(2);
            }

            int numCharsPerByte = numBase == NumberBase.Binary ? BitsPerByte : 2;
            int numCharsTotal   = textValue.Length;

            // I'm depending on the truncation of integer division here.
            int  numWholeBytes         = numCharsTotal / numCharsPerByte;
            int  numLeftoverCharacters = numCharsTotal % numCharsPerByte;
            bool validLength           = numWholeBytes == numRequiredBytes && numLeftoverCharacters == 0;

            // If necessary, we can pad up to the number of required bytes, but we can never truncate.
            if (!validLength && numWholeBytes < numRequiredBytes)
            {
                int numRequiredChars = numCharsPerByte * numRequiredBytes;
                if (byteOrder == NumberByteOrder.Numeric)
                {
                    textValue   = new string('0', numRequiredChars - numCharsTotal) + textValue;
                    validLength = true;
                }
                else
                {
                    // For big and little endian, we'll left pad up to the next full byte, then we'll right pad the rest of the data.
                    // This seems the most reasonable strategy since entering a single byte's data is a "Numeric" entry, which
                    // normally zero pads on the left.  But since Endianness deals with storage and we enter data from left to
                    // right, it seems reasonable to zero pad on the right to fill up the remaining unspecified bytes. For example,
                    // if "F" is entered for a Hex Int32, we'll left pad that up to "0F" and then right pad it to "0F000000".
                    int numLeftPadChars = numLeftoverCharacters == 0 ? 0 : numCharsPerByte - numLeftoverCharacters;
                    textValue = new string('0', numLeftPadChars) + textValue + new string('0', numRequiredChars - numCharsTotal - numLeftPadChars);

                    validLength = true;
                }
            }

            return(validLength);
        }