字符串转化为二进制数组
String s = "我是山东师范大学的一名学生。";
byte[] nn = new byte[0];
try {
nn = (s).getBytes("UTF-8");//可更改为Unicode、ASCII编码
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int wlen1= nn.length;
String wm1 ="";
for (int k = 0; k < wlen1; k++) {
byte b = nn[k];
String result = "";
byte a = b;
for (int i = 0; i < 8; i++) {
byte c = a;
a = (byte) (a >> 1);//每移一位如同将10进制数除以2并去掉余数。
a = (byte) (a << 1);
if (a == c) {
result = "0" + result;
} else {
result = "1" + result;
}
a = (byte) (a >> 1);
}
wm1 =new StringBuilder(wm1).append(result).toString();
}
char[] wm2=wm1.toCharArray();
int []wm3=new int[wm1.length()];
for (int k = 0; k < wm1.length(); k++) {
wm3[k] =wm2[k]-48;//减去字符0的ascii码
}
二进制数组转换成字符串
char []wm5=new char[wm1.length()];
for (int k = 0; k < wm1.length(); k++) {
wm5[k] = (char)(wm3[k]+'0');//
}
String wm4=String.valueOf(wm5);
int size = wm1.length()/8;
//定义接收数组
byte[] bytes1 = new byte[size];
for (int i = 0; i < size; i++) {
//每次截取8位计算
String tmp = wm4.substring(8*i,8*(i+1));
int tmpInt = Integer.parseInt(tmp,2);
byte tmpByte = (byte)(tmpInt & 0xff);
bytes1[i] = tmpByte;
}
String str = new String(bytes1, Charset.forName("UTF-8"));
|