All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.azbh111.utils.java.math.RadixUtils Maven / Gradle / Ivy

The newest version!
package com.github.azbh111.utils.java.math;

import java.util.ArrayList;
import java.util.List;

/**
 * 进制相关
 * 只能处理非负数
 * @author pyz
 * @date 2019/4/14 12:03 AM
 */
public class RadixUtils {

    /**
     * 值value的radix进制指数表达形式
     * ratios[0]*radix^0 + ratios[1]*radix^1 + ratios[2]*radix^2 + ratios[3]*radix^3 + ...
     * 返回radios数组
     *
     * @param value
     * @param radix 进制
     * @return
     */
    public static int[] toRadixRatios(long value, int radix) {
        if (radix < 2) {
            throw new IllegalArgumentException(radix + "");
        }
        List ratios = new ArrayList<>();
        int mod;
        while (value != 0) {
            mod = (int) (value % radix);
            ratios.add(mod);
            value /= radix;
        }
        int[] ratioArr = new int[ratios.size()];
        int size = ratios.size();
        for (int i = 0; i < size; i++) {
            ratioArr[i] = ratios.get(i);
        }
        return ratioArr;
    }

    /**
     * 解析radix进制数的指数表达形式为数字
     * ratios[0]*radix^0 + ratios[1]*radix^1 + ratios[2]*radix^2 + ratios[3]*radix^3 + ...
     *
     * @param radix
     * @param ratios 系数
     * @return
     */
    public static long valueOf(int radix, int[] ratios) {
        long r = 0;
        for (int i = 0; i < ratios.length; i++) {
            r = r + ratios[i] * MathUtils.powIntegralL(radix, i);
        }
        return r;
    }

    /**
     * value的radix进制指数表达形式
     * ratios[0]*radix^0 + ratios[1]*radix^1 + ratios[2]*radix^2 + ratios[3]*radix^3 + ...
     * 计算ratios[index]的值
     *
     * @param value
     * @param radix 进制
     * @param index from 0
     * @return
     */
    public static int numberAt(long value, int radix, int index) {
        long subNumber = MathUtils.powIntegralL(radix, index);
        value = value / subNumber;
        return (int) (value % radix);
    }

    /**
     * 指定数字的radix进制形式
     *
     * @param value
     * @param radix 进制
     * @return
     */
    public static String toString(long value, int radix) {
        return Long.toString(value, radix);
    }

    /**
     * 指定数字的radix进制形式的第index位的数字是多少
     *
     * @param value
     * @param radix 进制
     * @return
     */
    public static String toString(int value, int radix) {
        return Integer.toString(value, radix);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy