/**
* @Author lidonggui
* @Date 2021/7/13 15:54
* @Version 1.0
*/
public class BlobUtils {
/**
* 将字符转为二进制
*
* @param str 输入待转换的字符串
*/
public static String toBinary(String str) {
char[] strChar = str.toCharArray();
String result = "";
for (int i = 0; i < strChar.length; i++) {
result += Integer.toBinaryString(strChar[i]) + " ";
}
return result;
}
/**
* 将二进制字符串转换成int数组
* @param binStr 二進制字符串
* @return
*/
public static int[] BinstrToIntArray(String binStr) {
char[] temp = binStr.toCharArray();
int[] result = new int[temp.length];
for (int i = 0; i < temp.length; i++) {
result[i] = temp[i] - 48;
}
return result;
}
/**
* 将二进制转换成字符
* @param binStr 二進制串
* @return
*/
public static char BinstrToChar(String binStr) {
int[] temp = BinstrToIntArray(binStr);
int sum = 0;
for (int i = 0; i < temp.length; i++) {
sum += temp[temp.length - 1 - i] << i;
}
return (char) sum;
}
/**
* 將二進制转化为字符
*
* @param binStr
*/
public static char[] BinstrToStr(String binStr) {
String[] tempStr = binStr.split(" ");
char[] tempChar = new char[tempStr.length];
for (int i = 0; i < tempStr.length; i++) {
tempChar[i] = BinstrToChar(tempStr[i]);
}
return tempChar;
}
}
使用
-
字符串转化为二进制:
String res = BlobUtils.toBinary( value);
-
将二进制转化为字符串
char[] chars = BlobUtils.BinstrToStr(二进制串); String res = String.valueOf(chars);