(4)“密码”“MAC码”等数据由于是二进制数据,在Java中只能以byte[]形式存放,
但往往需要转化成可见字符串在通讯报文(如XML)中传递。
例如,密文: byte[] password = {0x5A,0x08,0x00,0xFF,0xB2,0x33,0xDE,0xFF};
转化为字符串:"5A0800FFB233DEFF"
请编程实现方法byte2HexString完成这种转化:
public String byte2HexString(byte[] b)
注:字符'A'的数值为0x41,字符'0'的数值为0x30
今天老师留了作业,大家帮忙看看
但往往需要转化成可见字符串在通讯报文(如XML)中传递。
例如,密文: byte[] password = {0x5A,0x08,0x00,0xFF,0xB2,0x33,0xDE,0xFF};
转化为字符串:"5A0800FFB233DEFF"
请编程实现方法byte2HexString完成这种转化:
public String byte2HexString(byte[] b)
注:字符'A'的数值为0x41,字符'0'的数值为0x30
今天老师留了作业,大家帮忙看看
public static void main(String args[]){
byte[] c={(byte)0x5A,(byte)0x08,(byte)0x00,(byte)0xFF,(byte)0xB2,(byte)0x33,(byte)0xDE,(byte)0xFF};
System.out.println (ByteToString.byte2HexString(c));
}
public static String byte2HexString(byte []c){
StringBuffer sb=new StringBuffer();
for (int i = 0; i<c.length; i++) {
String s=(String.format("%x",(int)c[i]&0xFF)).toUpperCase();
if(s.length()<2){
sb.append("0");
}
sb.append(s);
}
return sb.toString();
}
}
package net.java2000.tools;public class ByteTools {
/**
* byte转化为字符串输出
*
* @param b
* @return
*/
public static String byteToString(byte b) {
byte high, low;
byte maskHigh = (byte) 0xf0;
byte maskLow = 0x0f;
high = (byte) ((b & maskHigh) >> 4);
low = (byte) (b & maskLow);
StringBuffer buf = new StringBuffer();
buf.append(findHex(high));
buf.append(findHex(low));
return buf.toString();
} public static String byteToString(byte[] bs) {
byte high, low;
byte maskHigh = (byte) 0xf0;
byte maskLow = 0x0f;
StringBuffer buf = new StringBuffer();
for (byte b : bs) {
high = (byte) ((b & maskHigh) >> 4);
low = (byte) (b & maskLow);
buf.append(findHex(high));
buf.append(findHex(low));
}
return buf.toString();
} public static int stringToByte(String in, byte[] b) throws Exception {
if (b.length < in.length() / 2) {
throw new Exception("byte array too small");
}
int j = 0;
StringBuffer buf = new StringBuffer(2);
for (int i = 0; i < in.length(); i++, j++) {
buf.insert(0, in.charAt(i));
buf.insert(1, in.charAt(i + 1));
int t = Integer.parseInt(buf.toString(), 16);
System.out.println("byte hex value:" + t);
b[j] = (byte) t;
i++;
buf.delete(0, 2);
}
return j;
} private static char findHex(byte b) {
int t = new Byte(b).intValue();
t = t < 0 ? t + 16 : t;
if ((0 <= t) && (t <= 9)) {
return (char) (t + '0');
}
return (char) (t - 10 + 'A');
}
}