java base64 to hex_How to implement string conversion Base64 to Hex in java equal to given JS implem...

I'm trying to implement a string conversion from Base64 to Hex, that must yield the same results as

this website. Which means for example (Base64: bACAAAAAAAA=) is deconverted to (Hex: 6c00800000000000). This implementation in Javascript yields the correct output. So I tried to implement the equivalent in Java:

private static String base64ToHex(String input) {

byte[] raw = Base64.getDecoder().decode(input.getBytes());

String result = "";

for (int i = 0; i < raw.length; i++) {

String hex = Integer.toString(raw[i], 16);

result += (hex.length() == 2 ? hex : '0' + hex);

}

return result.toUpperCase();

}

Unfortunately this does not give the required output. So could you please give me hint about what I am missing?

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

Try below - You need to decode, not encode. Consider only value from decoded, ignore sign part. i.e take only absolute value, using Math.abs().

private static String base64ToHex(String input) {

byte[] raw = Base64.getDecoder().decode(input.getBytes());

String result = "";

for (int i = 0; i < raw.length; i++) {

String hex = Integer.toString(Math.abs(raw[i]), 16);

result += (hex.length() == 2 ? hex : '0' + hex);

}

return result.toUpperCase();

}

# Answer 2

private static String base64ToHex(String input) {

byte[] raw = Base64.getDecoder().decode(

input.getBytes(StandardCharsets.US_ASCII));

StringBuilder result = new StringBuilder(raw.length * 2);

for (byte b : raw) {

result.append(String.format("%02X", b & 0xFF));

}

return result.toString();

}

The problem is that java byte is signed, hence the masking & 0xFF.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值