You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将Base64字符串转换为十六进制?已尝试代码但无效

如何将Base64字符串转换为十六进制?

你的代码思路其实是对的,但没法运行大概率是因为缺少Apache Commons Codec依赖或者类导入不正确导致的。我来帮你一步步解决这个问题:

1. 确保添加了Apache Commons Codec依赖

如果你用Maven,在pom.xml里加入以下依赖:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version> <!-- 用最新稳定版即可 -->
</dependency>

如果是Gradle,在build.gradle里添加:

implementation 'commons-codec:commons-codec:1.15'

2. 正确导入所需类

在你的Java文件顶部导入这两个类:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

3. 修正后的完整代码

把你的代码放到完整的类里,比如:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class Base64ToHex {
    public static void main(String[] args) {
        String guid = "YxRfXk827kPgkmMUX15PNg=="; 
        byte[] decoded = Base64.decodeBase64(guid); 
        String hexString = Hex.encodeHexString(decoded); 
        System.out.println(hexString); // 输出应该是:63145f5e4f36ee43e0a498c517d793d6
    }
}

4. 不用第三方库的方案(JDK原生API)

如果不想引入外部依赖,JDK 8及以上自带java.util.Base64,但需要自己实现十六进制转换逻辑:

import java.util.Base64;

public class Base64ToHexNative {
    public static void main(String[] args) {
        String guid = "YxRfXk827kPgkmMUX15PNg==";
        // 解码Base64为字节数组
        byte[] decodedBytes = Base64.getDecoder().decode(guid);
        // 转换为十六进制字符串
        String hexString = bytesToHex(decodedBytes);
        System.out.println(hexString); // 同样输出:63145f5e4f36ee43e0a498c517d793d6
    }

    // 手动实现字节数组转十六进制的工具方法
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

内容的提问来源于stack exchange,提问作者user2433953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:20:43