2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Kotlin】16進数文字列をByte配列に変換する

Posted at

初めに

16進数文字列とは、0~9,a~f で書かれた文字列。なので、1文字あたり4bitで構成可能。
4bit per one →8bit(1byte) per one の変換となるので、Byte配列に変換するには16進数文字列の長さが偶数である必要がある。

コード

ここに書いてある通り。

sample.kt
fun String.decodeHex(): ByteArray {
    check(length % 2 == 0) { "Must have an even length" }

    return chunked(2)
        .map { it.toInt(16).toByte() }
        .toByteArray()
}

chunked関数初めて知りました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?