小写英文字符转换为16进制字符串再转为byte数组,在转回String时出现乱码
public class Test {
public static void main(String[] args){
String s1 = "sunhaowei";
String s2 = convertDecimalToHex(asciiToDecimal(s1));
System.out.println(s2);
String s3 = "SUNHAOWEI";
String s4 = convertDecimalToHex(asciiToDecimal(s3));
System.out.println(s4);
byte[] b1 = hexStringToBytes(s2);
System.out.println(new String(b1));
byte[] b2 = hexStringToBytes(s4);
System.out.println(new String(b2));
}
/**
* 将16进制str转换为10进制格式的字符串
*
* 例如:
* 十六进制 120418
* 十进制 180424
*/
public static String convertHexToDecimal(String str) {
String hex = "";
String pattern = "%02d";
for(int i=0; i<str.length()/2; i++) {
hex += String.format(pattern,Integer.parseInt(str.substring(i*2,i*2+2),16));
}
return hex;
}
/**
* 将10进制str转换为16进制格式的字符串
*
* 例如:
* 十进制 180424
* 十六进制 120418
*/
public static String convertDecimalToHex(String str) {
String hex = "";
String pattern = "%02x";
for(int i=0; i<str.length()/2; i++) {
hex += String.format(pattern, Integer.valueOf(str.substring(i*2,i*2+2)));
}
return hex;
}
/**
* 将ASCII码转换为10进制str
*/
public static String asciiToDecimal(String value) {
StringBuffer sbu = new StringBuffer();
char[] ch = value.toCharArray();
for (int i = 0; i < ch.length; i++) {
sbu.append((int)ch[i]);
}
return sbu.toString();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
// toUpperCase将字符串中的所有字符转换为大写
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
// toCharArray将此字符串转换为一个新的字符数组。
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
//charToByte返回在指定字符的第一个发生的字符串中的索引,即返回匹配字符
public static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
相关推荐
C#_string_byte数组转换解析
C# string byte数组转换解析 C# string byte数组转换实现的过程是什么呢?C# string byte数组间的转换需要注意什么呢?C# string byte数组间转换所涉及的方法是什么呢?让我们来看看具体的内容: C# string byte数组转换之string类型转成byte[]: byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str ); 反过来,byte[]转成string: string str = System.Text.Encoding.Default.GetString ( byteArray ); 其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;例如: string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31}) 1 byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str ); ASCII byte[] 转成string:(byte[] = new byte[]{ 0x30, 0x31} 转成 "01") 2 string str = System.Text.Encoding.ASCII.GetString ( byteArray ); 有时候还有这样一些需求: byte[] 转成原16进制格式的string,例如0xae00cf, 转换成 "ae00cf";new byte[]{ 0x30, 0x31}转成"3031":
String 与byte[] 间的转换
更好的解决了String类型与byte类型的转换,防止出现乱码问题
java中String_十六进制String_byte[]之间相互转换
java中String_十六进制String_byte[]之间相互转换
Java中字符串与byte数组之间的相互转换
Java语言中字符串类型和字节数组类型相互之间的转换经常发生,网上的分析及代码也比较多,这篇文章将主要介绍Java中字符串与byte数组之间的相互转换,有需要的朋友们可以参考借鉴,下面来一起看看吧。
C#中Byte[]和String之间转换的方法
很多朋友不清楚如何在Byte[]和String之间进行转换?下面小编给大家带来了byte与string转换的方法,感兴趣的朋友参考下吧


