프로그래밍 언어/코틀린(Kotline)

코틀린(Kotlin) 진법 변환 .toInt()

나아가는중 2023. 2. 27. 22:44
반응형

문자열 -> N진법 변환

코틀린에서 문자열을 N진법으로 변환하는 방법은 .toInt() 함수를 사용하는 방법이 있습니다.

 

코틀린 라이브러리를 확인해 보면 코틀린 1.1 버전부터 사용이 가능하며, 내부적으로는 자바의 .parseInt() 함수를 사용하고 있습니다.

/**
 * Parses the string as an [Int] number and returns the result.
 * @throws NumberFormatException if the string is not a valid representation of a number.
 * @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public actual inline fun String.toInt(radix: Int): Int = java.lang.Integer.parseInt(this, checkRadix(radix))

 

 

.parseInt의 파라미터 checkRadix() 함수가 존재하는데, 이 함수는 파라미터로 넘어온 radix가 MIN_RADIX(2) 와 MAX_RADIX(36)의 사이인지 검사해서 사이 값으라면 radix를 반환하는 함수입니다.

@PublishedApi
internal actual fun checkRadix(radix: Int): Int {
    if (radix !in Character.MIN_RADIX..Character.MAX_RADIX) {
        throw IllegalArgumentException("radix $radix was not in valid range ${Character.MIN_RADIX..Character.MAX_RADIX}")
    }
    return radix
}

 

.parseInt() 함수의 내부에서는 다음과 같은 로직을 통해 radix 로 지정한 N진법으로 변환을 해주게 됩니다.

    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        ...
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;

        if (len > 0) {
            ...
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
            return negative ? result : -result;
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }

 

반응형