Java中字符串与byte数组之间的相互转换
前⾔
Java与其他语⾔编写的程序进⾏tcp/ip socket通讯时,通讯内容⼀般都转换成byte数组型,java在字符与数组转换也是⾮常⽅便的。下⾯跟我⼀起来了解⼀下字符串与byte之间转换的原理
原理
我们都知道,在Java⾥byte类型是占⽤1个字节,即8位的,⽽16进制的字符占⽤4位,所以每个byte可以⽤两个字符来表⽰,反之亦然。
举个例⼦
byte = 123
⽤⼆进制表⽰:0111 1011
每4位⽤字符表⽰:7 b
是的,原理就这么简单,接下来⽤代码实现:
byte[] 转16进制字符串
⽅法⼀
思路:先把byte[] 转换维char[],再把char[]转换为字符串
public static String bytes2Hex(byte[] src) {
if (src == null || src.length <= 0) {
return null;
}
char[] res = new char[src.length * 2]; // 每个byte对应两个字符
final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
for (int i = 0, j = 0; i < src.length; i++) {
res[j++] = hexDigits[src[i] >> 4 & 0x0f]; // 先存byte的⾼4位
res[j++] = hexDigits[src[i] & 0x0f]; // 再存byte的低4位
}
return new String(res);
}
⽅法⼆
思路:先把byte转换为int类型,再转换为字符串
public static String bytesToHex(byte[] src){
if (src == null || src.length <= 0) {
return null;
}
StringBuilder stringBuilder = new StringBuilder("");
for (int i = 0; i < src.length; i++) {
// 之所以⽤byte和0xff相与,是因为int是32位,与0xff相与后就舍弃前⾯的24位,只保留后8位
String str = HexString(src[i] & 0xff);
if (str.length() < 2) { // 不⾜两位要补0
stringBuilder.append(0);
}
stringBuilder.append(str);
}
String();
}
16进制字符串转byte[]
思路:先把字符串转换为char[] ,再转换为byte[]
public static byte[] hexToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
int length = hexString.length() / 2;
char[] hexChars = CharArray();
byte[] bytes = new byte[length];
String hexDigits = "0123456789abcdef";
for (int i = 0; i < length; i++) {
int pos = i * 2; // 两个字符对应⼀个byte
int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
if(h == -1 || l == -1) { // ⾮16进制字符
return null;
}
bytes[i] = (byte) (h | l);
}
return bytes;
}
注:注1得到xxxx0000,注2得到0000xxxx,相或就把两个字符转换为⼀个byte了。
数组格式字符串转数组
再举个例⼦
md5加密
public static String getMd5ByFile(File file) {
String ret= null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
MessageDigest md = Instance("MD5");
byte[] buffer = new byte[1024];
int len;
while((len = ad(buffer)) > 0) {
md.update(buffer, 0, len);
}
ret = bytes2Hex(md.digest()); // 把md5加密后的byte[]转换为字符串
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ret;
}
总结
好了,应该懂了吧,其实并不难的。以上就是这篇⽂章的全部内容了,希望这篇⽂章的内容对⼤家的学习或者⼯作能带来⼀定的帮助,如果有疑问⼤家可以留⾔交流。

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