在 Java 中将十六进制字符串转换为 ASCII [英] Convert a String of Hex into ASCII in Java

查看:173
本文介绍了在 Java 中将十六进制字符串转换为 ASCII的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这不是一个太愚蠢的问题,我查看了 5 个不同的 Google 结果页面,但没有找到任何相关信息.

I hope this isn't too much of a stupid question, I have looked on 5 different pages of Google results but haven't been able to find anything on this.

我需要做的是将包含所有十六进制字符的字符串转换为 ASCII 例如

What I need to do is convert a string that contains all Hex characters into ASCII for example

String fileName = 

75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000

我所看到的每一种方式都让您似乎必须先将其放入数组中.有没有办法遍历每两个并转换它们?

Every way I have seen makes it seems like you have to put it into an array first. Is there no way to loop through each two and convert them?

推荐答案

只需使用 for 循环遍历字符串中的每一对字符,将它们转换为一个字符,然后在字符串生成器的末尾敲击该字符:

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

<代码>字符串十六进制= 75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";StringBuilder 输出 = new StringBuilder();for (int i = 0; i

或者(Java 8+)如果你觉得特别粗鲁,可以使用臭名昭著的固定宽度字符串拆分"技巧来让你用流来做一个单行:

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

System.out.println(Arrays
        .stream(hex.split("(?<=\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
        .map(s -> Character.toString((char)Integer.parseInt(s, 16)))
        .collect(Collectors.joining()));

无论如何,这给出了几行以以下开头:

Either way, this gives a few lines starting with the following:

uTorrentCompleted fsuc_ost_by_mustangPendulum-9,000 Miles.mp3

uTorrentCompleted fsuc_ost_by_mustangPendulum-9,000 Miles.mp3

嗯... :-)

这篇关于在 Java 中将十六进制字符串转换为 ASCII的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆