Java 将 Base64 转换为十六进制字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41611248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:59:46  来源:igfitidea点击:

Java convert Base64 to Hex String

javahexbase64

提问by user3441151

I have one Base64 String YxRfXk827kPgkmMUX15PNg==I want to convert it into 63145F5E4F36EE43E09263145F5E4F36

我有一个 Base64 字符串,YxRfXk827kPgkmMUX15PNg==我想将其转换为63145F5E4F36EE43E09263145F5E4F36

So I think scenario would be like this I have to first decode Base64 string and than convert it into Hex

所以我认为场景是这样的,我必须首先解码 Base64 字符串,然后将其转换为十六进制

My code is given below

我的代码如下

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

String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.decodeBase64(guid);
try {
    System.out.println(new String(decoded, "UTF-8") + "\n");
} catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
}

Above code gives c_^O6?C??c_^O6

上面的代码给出 c_^O6?C??c_^O6

But I don't know How to convert this string into Hex string. So it gives the 63145F5E4F36EE43E09263145F5E4F36output.

但我不知道如何将此字符串转换为十六进制字符串。所以它给出了63145F5E4F36EE43E09263145F5E4F36输出。

So please help me to fix this issue.

所以请帮我解决这个问题。

回答by Shakti Dash

Since you are already using Apache Common Codec:

由于您已经在使用 Apache Common Codec:

String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.decodeBase64(guid);
String hexString = Hex.encodeHexString(decoded);
System.out.println(hexString);

Using standard Java libraries:

使用标准 Java 库:

String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.getDecoder().decode(guid);
System.out.println(String.format("%040x", new BigInteger(1, decoded)));

回答by Hemant Sangle

Hey try this code it gives the expected output

嘿试试这个代码它给出了预期的输出

import java.util.Base64;

/**
*
* @author hemants
*/
public class NewClass5 {

    public static void main(String[] args) {
        String guid = "YxRfXk827kPgkmMUX15PNg==";
        byte[] decoded = Base64.getDecoder().decode(guid);
        System.out.println(toHex(decoded));
    }
    private static final char[] DIGITS
            = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static final String toHex(byte[] data) {
        final StringBuffer sb = new StringBuffer(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            sb.append(DIGITS[(data[i] >>> 4) & 0x0F]);
            sb.append(DIGITS[data[i] & 0x0F]);
        }
        return sb.toString();
    }

}

Output

输出

63145F5E4F36EE43E09263145F5E4F36