import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ShowFloatBit extends JFrame implements ActionListener {
final JTextField[] fields = new JTextField[2];
final JButton button = new JButton("查看");
final JPanel panel = new JPanel();
public ShowFloatBit(String title) {
super(title);
fields[0] = new JTextField(10);
fields[1] = new JTextField(30);
panel.add(fields[0], FlowLayout.LEFT);
panel.add(button, FlowLayout.CENTER);
panel.add(fields[1], FlowLayout.RIGHT);
add(panel, BorderLayout.NORTH);
button.addActionListener(this);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new ShowFloatBit("浮点数二进制查看器");
float f = 3.14f;
int k = Float.floatToIntBits(f);
System.out.println(showIntBit(k));
}
public static int fromFloatToInt(float f) {
ByteArrayInputStream bis = null;
ByteArrayOutputStream bos = null;
DataInputStream dis = null;
DataOutputStream dos = null;
int n = 0;
try {
bos = new ByteArrayOutputStream(4);
dos = new DataOutputStream(bos);
dos.writeFloat(f);
bis = new ByteArrayInputStream(bos.toByteArray());
dis = new DataInputStream(bis);
n = dis.readInt();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null)
try {
dos.close();
} catch (IOException e) {
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
}
if (dis != null)
try {
dis.close();
} catch (IOException e) {
}
if (bis != null)
try {
bis.close();
} catch (IOException e) {
}
}
return n;
}
public static String showIntBit(int n) {
StringBuffer buffer = new StringBuffer();
for (int i = 31; i >= 0; i--) {
if ((n & (1 << i)) != 0) {
buffer.append("1");
} else {
buffer.append("0");
}
if ((32 - i) % 8 == 0) {
buffer.append(" ");
}
}
System.out.println();
return buffer.toString();
}
@Override
public void actionPerformed(ActionEvent e) {
float f = Float.parseFloat(fields[0].getText());
int n = fromFloatToInt(f);
fields[1].setText(showIntBit(n));
}
}