001/*
002 * The MIT License (MIT)
003 *
004 * Copyright (c) 2015-2023 decimal4j (tools4j), Marco Terzer
005 *
006 * Permission is hereby granted, free of charge, to any person obtaining a copy
007 * of this software and associated documentation files (the "Software"), to deal
008 * in the Software without restriction, including without limitation the rights
009 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010 * copies of the Software, and to permit persons to whom the Software is
011 * furnished to do so, subject to the following conditions:
012 *
013 * The above copyright notice and this permission notice shall be included in all
014 * copies or substantial portions of the Software.
015 *
016 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
017 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
018 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
019 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
020 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
021 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
022 * SOFTWARE.
023 */
024package org.decimal4j.arithmetic;
025
026import java.math.BigInteger;
027
028import org.decimal4j.scale.ScaleMetrics;
029
030
031/**
032 * Contains methods to convert from and to {@link BigInteger}.
033 */
034final class BigIntegerConversion {
035        
036        /**
037         * Converts the specified big integer value to an unscaled decimal value. An exception is thrown if the value
038         * exceeds the valid Decimal range.
039         * 
040         * @param scaleMetrics
041         *            the scale metrics of the result value
042         * @param value
043         *            the big integer value to convert
044         * @return the decimal value of the scale as defined by {@code ScaleMetrics}
045         * @throws IllegalArgumentException
046         *             if the value is outside of the valid Decimal range
047         */
048        public static final long bigIntegerToUnscaled(ScaleMetrics scaleMetrics, BigInteger value) {
049                if (value.bitLength() <= 63) {
050                        return LongConversion.longToUnscaled(scaleMetrics, value.longValue());
051                }
052                throw new IllegalArgumentException("Overflow: cannot convert " + value + " to Decimal with scale " + scaleMetrics.getScale());
053        }
054
055        // no instances
056        private BigIntegerConversion() {
057                super();
058        }
059}