진수 변환 함수 (62진수 까지)

페이지 정보

  • 조회 31
  • 작성일 2026.02.25 15:07

public final class NumberUtil {
 
    private static final char[] DIGITS = {
        '0','1','2','3','4','5','6','7','8','9',
        'a','b','c','d','e','f','g','h','i','j',
        'k','l','m','n','o','p','q','r','s','t',
        'u','v','w','x','y','z',
        'A','B','C','D','E','F','G','H','I','J',
        'K','L','M','N','O','P','Q','R','S','T',
        'U','V','W','X','Y','Z'
    };
 
    /**
     * 2 ~ 62 진법 변환 (최적화 버전)
     */
    public static String numberToBase(long num, int radix) {
 
        if (radix < 2 || radix > 62) {
            throw new IllegalArgumentException("radix는 2 이상 62 이하만 가능합니다.");
        }
 
        if (num == 0L) {
            return "0";
        }
 
        boolean negative = (num < 0L);
        long value = negative ? -num : num;
 
        // long 최대 자릿수: 64bit → 2진수 기준 64자리
        char[] buffer = new char[65];
        int index = buffer.length;
 
        while (value != 0L) {
            buffer[--index] = DIGITS[(int)(value % radix)];
            value /= radix;
        }
 
        if (negative) {
            buffer[--index] = '-';
        }
 
        return new String(buffer, index, buffer.length - index);
    }
}
[이 게시물은 이재민님에 의해 2026-03-04 13:54:35 개발에서 이동 됨]

댓글목록

등록된 댓글이 없습니다.