如下代码可实现将你所需要的任何信息转换成二进制代码形式
package com.kinghi.xlink.common.util.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* XAnyToBinary.java
*
* 将信息转换成二进制形式
*
* @author wanghy
* @version 1
* @since 2008.01.25
*/
public class XAnyToBinary {
public static XAnyToBinary stb = new XAnyToBinary();
public OutputStream os;
public File f;
public boolean getFile() {
f = new File("file.properties");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public OutputStream getOS() {
if (stb.getFile()) {
try {
os = new FileOutputStream(f, true) {
@SuppressWarnings("unused")
protected void writeStreamHeader() throws IOException {
}
};
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return os;
}
public void toBinary(String str) {
byte[] b = str.getBytes();
System.out.println("需要转换的信息是:" + str);
for (int j = 0; j < b.length; j++) {
System.out.print("b[" + j + "]= " + b[j] + " ASCII码是:");
int number = Integer.parseInt(String.valueOf(b[j]));
System.out.print("number= " + number + " 转化成32位的二进制后:");
stb.toBinary(number);
}
System.out.println();
}
public void toBinary(int v) {
String str = Integer.toBinaryString(v);
if (str.length() < 32) {
int t = 32 - str.length();
for (int j = 0; j < t; j++) {
str = "0" + str;
}
}
System.out.println(str);
os = stb.getOS();
if (os != null) {
try {
os.write(str.getBytes());
os.write("/r/n".getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
return;
}
}
public static void main(String[] args) {
int k = 2;
int m = -2;
stb.toBinary(",");
stb.toBinary(" ");
stb.toBinary("-7");
stb.toBinary("你好啊");
System.out.print("直接输入整数 " + k + " 转化成32位的二进制数是:");
stb.toBinary(k);
System.out.print("直接输入整数 " + m + " 转化成32位的二进制数是:");
stb.toBinary(m);
System.out
.println("-2转化成二进制的长度:" + Integer.toBinaryString(-2).length());
}
}