๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๊ณณ๊ฐ„์—์„œ ์ธ์‹ฌ๋‚œ๋‹ค/์Šคํ„ฐ๋””

[Kotlin][Java] ByteArrays๋ฅผ 16์ง„์ˆ˜(Hex) String์œผ๋กœ ๋ณ€ํ™˜

https://www.baeldung.com/kotlin/byte-arrays-to-hex-strings

์—ฌ๊ธฐ์— ์ •๋ง ์ž˜ ๋‚˜์™”์Œ.

 

๋‹ค์–‘ํ•œ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ–ˆ๋‹ค.

๊ทธ ์ค‘์—์„œ ๋‹ค์Œ์˜ ๋ฐฉ๋ฒ•์— ์ฃผ๋ชฉํ–ˆ๋‹ค.

https://www.baeldung.com/kotlin/byte-arrays-to-hex-strings

 

val hexChars = "0123456789abcdef".toCharArray()

fun ByteArray.toHex4(): String {
    val hex = CharArray(2 * this.size)
    this.forEachIndexed { i, byte ->
        val unsigned = 0xff and byte.toInt()
        hex[2 * i] = hexChars[unsigned / 16]
        hex[2 * i + 1] = hexChars[unsigned % 16]
    }

    return hex.joinToString("")
}

//์ถœ์ฒ˜ : https://www.baeldung.com/kotlin/byte-arrays-to-hex-strings#loops-and-bitwise-operations

 

ํ”„๋กœ์ ํŠธ๋ฅผ ๋’ค์ง€๋‹ค๊ฐ€ ๋ฐœ๊ฒฌํ•œ ์ž๋ฐ” ์ฝ”๋“œ์—์„œ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„๋˜์–ด ์žˆ๋Š” ๊ฒƒ๊ณผ ๊ฒฐ๊ตญ์—” ๋™์ผํ•˜๋‹ค๋Š” ๊ฒƒ์„ ์•Œ์•˜๋‹ค.

 

public static int getUniqueId(...) {
    ...
    byte[] hash;
    ...
    StringBuilder hex = new StringBuilder(hash.length * 2);
    
    for (byte b : hash) {
        if ((b & 0xFF) < 0x10) hex.append("0");
        hex.append(Integer.toHexString(b & 0xFF));
    }
    
    return ...
}

์š” ์ž๋ฐ” ์ฝ”๋“œ๋ฅผ ์ฝ”ํ‹€๋ฆฐ์œผ๋กœ ๋ณ€๊ฒฝํ•˜๊ธฐ ์œ„ํ•ด

Integer.toHexString()์€ ์–ด๋–ป๊ฒŒ ๋ณ€๊ฒฝํ•  ๊ฒƒ์ธ๊ฐ€?

 

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-string.html

 

toString - Kotlin Programming Language

 

kotlinlang.org

 

fun Byte.toString(radix: Int) : String ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋˜๊ฒ ๋‹ค.

> (b.toInt() & 0xFF).toString(16)

 

 

์ฝ”ํ‹€๋ฆฐ์—์„œ๋Š”

byte.toInt() and 0xFF

์ž๋ฐ”์—์„œ๋Š” 

byte & 0xFF

์„ ์จ์„œ byte๋ฅผ ์–‘์ˆ˜๋กœ ํ‘œํ˜„์‹œํ‚จ๋‹ค. ์Œ์ˆ˜ ๋ถ€ํ˜ธ์˜ ๋น„ํŠธ๋งŒ ๋’ค์ง‘๋Š”๋‹ค. 

https://www.baeldung.com/kotlin/byte-arrays-to-hex-strings#loops-and-bitwise-operations

์š”๊ธฐ์— ์„ค๋ช…์ด ์ž˜ ๋‚˜์™€์žˆ๋‹ค.