如何在Kotlin中正确将指定十六进制值转换为Base64?
Let's break down what's going wrong with your current code, then fix it step by step.
The Problem with Your Current Approach
Your code is taking the hex string as plain UTF-8 text, converting those characters to bytes, then Base64 encoding that. That's not what you want—you need to first decode the hex string into the raw binary bytes it represents, then Base64 encode those bytes.
For example, the hex pair "26" should become the single byte 0x26, not the two UTF-8 bytes for the characters '2' (0x32) and '6' (0x36). That's why your output is way longer than expected.
The Correct Solution
We need to split this into two clear steps:
- Decode the hex string into a byte array
- Base64 encode that byte array
Implementation Examples
Option 1: For Android Projects (Using Android SDK Utilities)
Android provides built-in classes to handle both hex decoding and Base64 encoding:
import android.util.Base64 import android.util.Hex fun main() { val hexInput = "263e5df7a93ec5f5ea6ac215ed957c30" // Step 1: Convert hex string to raw bytes val rawBytes = Hex.decode(hexInput) // Step 2: Encode raw bytes to Base64 val correctBase64 = Base64.encodeToString(rawBytes, Base64.NO_WRAP) println(correctBase64) // Outputs: Jj5d96k+xfXqasIV7ZV8MA== }
Option 2: Pure Kotlin/JVM (No External Dependencies)
If you're working on a non-Android Kotlin project, you can implement a simple hex-to-byte function yourself, then use Java's standard Base64 library:
import java.util.Base64 // Extension function to convert hex string to byte array fun String.hexToByteArray(): ByteArray { require(length % 2 == 0) { "Hex string must have an even number of characters" } return chunked(2) .map { hexPair -> hexPair.toInt(16).toByte() } .toByteArray() } fun main() { val hexInput = "263e5df7a93ec5f5ea6ac215ed957c30" val rawBytes = hexInput.hexToByteArray() val correctBase64 = Base64.getEncoder().encodeToString(rawBytes) println(correctBase64) // Outputs: Jj5d96k+xfXqasIV7ZV8MA== }
Key Notes
- The
hexToByteArrayextension function splits the input string into 2-character chunks, converts each chunk from base-16 to a byte, and collects those into a byte array. - For Base64 encoding, we're using the standard library implementations (Android's
Base64or Java'sjava.util.Base64) to ensure compatibility and correctness.
内容的提问来源于stack exchange,提问作者Jim Clermonts

