浮点数查看器

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)); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值