汉字字符串转换成⼗六进制byte数组,⼀个汉字存到两个byte⾥
⾯,⼤整数存到两个byte⾥⾯
package st;
/**
* 汉字字符串转换成⼗六进制byte数组,⼀个汉字存到两个byte⾥⾯,⼤整数存到两个byte⾥⾯
* @author zhengdunzhuang
*
*/
public class ChineseCharacterStringToByteArray {
public static void main(String[] args) {
byte[] data = new byte[42];
data[0] = (byte) 0x04;
data[1] = (byte) (42);
printHexString(data);
System.out.println("");
String msg = "你已成功添加李先⽣为好友";
data = toHexByteByStrings(data,3,msg);
printHexString(data);
/*
* ⽤⼯具转换需要的结果:
你已成功添加李先⽣为好友
{0x4f60,0x5df2,0x6210,0x529f,0x6dfb,0x52a0,0x674e,0x5148,0x751f,0x4e3a,0x597d,0x5 3cb,0x0};
打印输出结果:
042A00000000000000000000000000000000000000000000000000000000000000000000000000000000
042A4F605DF26210529F6DFB52A0674E5148751F4E3A597D53CB00000000000000000000000000000000
4F60
*/
int i = 20320;//0x4f60
byte[] b = intToByteArray(i);
System.out.println("");
printHexString(b);
}
//整数转换成byte数组
public static byte[] intToByteArray(int i) {
byte[] result = new byte[2];
result[0] = (byte) ((i & 0xFF00) >> 8 );
result[1] = (byte) ( i & 0xFF);
return result;
}
/**
* 转化汉字字符串为⼗六进制编码并放到byte数组⾥⾯,⼀个字符两个byte字节
* @param data byte数组
* @param start 要追加的开始个数,从1算起,如从byte[3]开始则start=4
* @param s 要转换的字符串
* @return
字符串数组怎么转成byte*/
public static byte[] toHexByteByStrings(byte[] data,int start,String s) {
int j = start;
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
data[j-1] = (byte) ((ch & 0xFF00) >> 8 );
data[j] = (byte) ( ch & 0xFF);
j += 2;
}
return data;
}
// 转化字符串为⼗六进制编码字符串
public static String toHexByStrings(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = HexString(ch);
str = str + s4;
}
return str;// 0x表⽰⼗六进制
}
/
/打印⼗六进制字符串
public static void printHexString(byte[] b) {
for (int i = 0; i < b.length; i++) {
String hex = HexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.UpperCase());
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。