当前位置:   article > 正文

字符串与二进制字符流之间相互转换,JAVA_二进制字符串流

二进制字符串流
  1. private static String[] PREFIX_POOL = {"0", "00", "000", "0000", "00000", "000000", "0000000", "00000000",
  2. "000000000", "0000000000", "00000000000", "000000000000",
  3. "0000000000000", "00000000000000", "000000000000000"
  4. };
  5. /**
  6. * 字符串转换成二进制流
  7. *
  8. * @param str 字符串
  9. * @return 二进制流
  10. */
  11. private static String toBinary(String str) {
  12. if (null == str || str.trim().length() == 0) {
  13. return null;
  14. }
  15. char[] strChar = str.toCharArray();
  16. StringBuilder result = new StringBuilder(strChar.length << 4);
  17. for (int i = 0; i < strChar.length; i++) {
  18. // 二进制ASCII码
  19. String s = Integer.toBinaryString(strChar[i]);
  20. // 补0
  21. if (s.length() < 16) {
  22. s = PREFIX_POOL[15 - s.length()].concat(s);
  23. }
  24. result.append(s);
  25. }
  26. return result.toString();
  27. }
  28. /**
  29. * 二进制流转换成字符串
  30. *
  31. * @param binaryString 二进制流
  32. * @return 字符串
  33. */
  34. private static String toString(String binaryString) {
  35. if (null == binaryString || binaryString.trim().length() == 0) {
  36. return null;
  37. }
  38. int len = binaryString.length();
  39. StringBuilder sb = new StringBuilder(len >> 4);
  40. int step = 16;
  41. for (int i = 0; i < len; i += step) {
  42. // 将ascll码强转成字符
  43. sb.append((char) (int) Integer.parseInt(binaryString.substring(i, i + step), 2));
  44. }
  45. return sb.toString();
  46. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/618031
推荐阅读
相关标签
  

闽ICP备14008679号