当前位置: 移动技术网 > IT编程>开发语言>Java > Java中字符串与byte数组之间的相互转换

Java中字符串与byte数组之间的相互转换

2019年07月22日  | 移动技术网IT编程  | 我要评论

前言

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 = integer.tohexstring(src[i] & 0xff); 
   if (str.length() < 2) { // 不足两位要补0
    stringbuilder.append(0); 
   } 
   stringbuilder.append(str); 
  } 
  return stringbuilder.tostring(); 
 }

16进制字符串转byte[]

思路:先把字符串转换为char[] ,再转换为byte[]

 public static byte[] hextobytes(string hexstring) { 
  if (hexstring == null || hexstring.equals("")) { 
   return null; 
  } 

  int length = hexstring.length() / 2; 
  char[] hexchars = hexstring.tochararray(); 
  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 = messagedigest.getinstance("md5");
   byte[] buffer = new byte[1024];
   int len;
   while((len = fis.read(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;
 }

总结

好了,应该懂了吧,其实并不难的。以上就是这篇文章的全部内容了,希望这篇文章的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网