如何在java中将十六进制字符串转换为ascii [英] How to convert hex string to ascii in java

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

问题描述



我在java中将十六进制字符串转换为ascii字符串时遇到问题,即如果用户输入06,我的应用程序应将其转换为0x30 0x36并传递此值到一个字节数组。请帮帮我....

Hi,
I have a problem in converting hex string to ascii string in java, i.e. if the user enters "06", my application should convert it to "0x30 0x36" and pass this value to a byte array. Please help me out....

推荐答案

这并不意味着Hex string to ASCII。 Java字符串不是ASCII,它们使用Unicode。 ASCII代码是您对用户的期望,以数字字符串的形式,无论是十六进制还是十进制,并且在输出时您需要字符。

此外,您需要验证用户输入,以允许只有(可打印)字符,或者您应该以其他方式呈现不可打印的字符。



首先,您需要将用户输入的字符串解析为数值,一个字节,例如,

It does not mean "Hex string to ASCII". Java strings are not ASCII, they use Unicode. ASCII codes is what you expect from the user, in the form of numeric string, no matter hexadecimal or decimal, and on output you need characters.
Also, you need to validate the user input, to allow only (printable) characters, or you should present non-printable characters in some other way.

First, you need to parse string entered by the user to the numeric value, a byte, for example,
String input;
//...
byte value = Byte.parseByte(input, 16);

http://docs.oracle.com/javase/7/docs/api/java/lang /Byte.html#parseByte(java.lang.String) [ ^ ],

http://docs.oracle.com/javase/7/docs/api/java/lang /Byte.html#parseByte(java.lang.String,%20int) [ ^ ]。



注意使用第二个函数,您可以选择预期输入的基数。同样,解析可能会失败。当你得到一个值时,你只需要将它转换为一个字符:

http://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte(java.lang.String)[^],
http://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte(java.lang.String,%20int)[^].

Note that, with the second function, you can choose the radix of expected input. Again, parsing can fail. When you get a value, you just need to typecast it to a character:

char output = (char)value;



同样,获得的字符可能无法打印;所以验证价值并决定如何处理。



-SA


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

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