JAVA串口通讯程序
package com.jetf.serialport;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
import javax.imageio.ImageIO;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import com.jetf.mm.CRC16;
import com.jfinal.kit.StrKit;
public class JavaRs232 extends JFrame implements ActionListener,
SerialPortEventListener {
/**
* JDK Serial Version UID
*/
private static final long serialVersionUID = -7270865686330790103L;
protected int WIN_WIDTH = 500;
protected int WIN_HEIGHT = 420;
private JComboBox portCombox, rateCombox, dataCombox, stopCombox,
parityCombox, parityCombox1;
private Button openPortBtn, closePortBtn, sendMsgBtn, sendMsgBtn1;
private TextField sendTf;
private TextField sendD1;
private TextField sendD2;
private TextField sendD3;
private TextField sendTf1;
private TextArea readTa;
private JLabel statusLb;
private String portname, rate, data, stop, parity;
protected CommPortIdentifier portId;
protected Enumeration<?> ports;
protected List<String> portList;
protected SerialPort serialPort;
protected OutputStream outputStream = null;
protected InputStream inputStream = null;
protected String mesg;
protected String mesg1;
protected String mesg_info_D1;
protected String mesg_info_D2;
protected String mesg_info_D3;
protected String[] mesgs;
protected int sendCount, reciveCount;
/**
* 默认构造函数
*/
public JavaRs232() {
super("Java串口通信测试程序");
setSize(WIN_WIDTH, WIN_HEIGHT);
setLocationRelativeTo(null);
Image icon = null;
try {
icon = ImageIO.read(JavaRs232.class
.getResourceAsStream("rs232.png"));
} catch (IOException e) {
showErrMesgbox(e.getMessage());
}
setIconImage(icon);
setResizable(false);
scanPorts();
initComponents();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* 初始化各UI组件
*
* @since 2012-3-22 下午11:56:39
*/
public void initComponents() {
// 共用常量
Font lbFont = new Font("微软雅黑", Font.TRUETYPE_FONT, 14);
// 创建左边面板
JPanel northPane = new JPanel();
northPane.setLayout(new GridLayout(1, 1));
// 设置左边面板各组件
JPanel leftPane = new JPanel();
leftPane.setOpaque(false);
leftPane.setLayout(new GridLayout(3, 2));
JLabel portnameLb = new JLabel("串口号:");
portnameLb.setFont(lbFont);
portnameLb.setHorizontalAlignment(SwingConstants.RIGHT);
portCombox = new JComboBox((String[]) portList.toArray(new String[0]));
portCombox.addActionListener(this);
JLabel databitsLb = new JLabel("数据位:");
databitsLb.setFont(lbFont);
databitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
// 设置中间面板各组件
dataCombox = new JComboBox(new Integer[] { 5, 6, 7, 8 });
dataCombox.setSelectedIndex(3);
dataCombox.addActionListener(this);
JLabel parityLb = new JLabel("校验位:");
parityLb.setFont(lbFont);
parityLb.setHorizontalAlignment(SwingConstants.RIGHT);
parityCombox = new JComboBox(new String[] { "NONE", "ODD", "EVEN",
"MARK", "SPACE" });
parityCombox.addActionListener(this);
JLabel parityLb1 = new JLabel("01写:");
parityLb1.setFont(lbFont);
parityLb1.setLayout(new GridLayout(1, 1));
parityLb1.setHorizontalAlignment(SwingConstants.RIGHT);
// 设置中间面板各组件
sendD1 = new TextField(5);
JLabel parityLb2 = new JLabel("03读:");
parityLb2.setFont(lbFont);
parityLb2.setLayout(new GridLayout(1, 1));
parityLb2.setHorizontalAlignment(SwingConstants.RIGHT);
// 设置中间面板各组件
sendD3 = new TextField(5);
JLabel parityLb3 = new JLabel("0002:");
parityLb3.setFont(lbFont);
parityLb3.setLayout(new GridLayout(1, 1));
parityLb3.setHorizontalAlignment(SwingConstants.RIGHT);
// 设置中间面板各组件
sendD2 = new TextField(5);
// 添加组件至面板
leftPane.add(portnameLb);
leftPane.add(portCombox);
leftPane.add(databitsLb);
leftPane.add(dataCombox);
leftPane.add(parityLb);
leftPane.add(parityCombox);
leftPane.add(parityLb1);
leftPane.add(sendD1);
leftPane.add(parityLb2);
leftPane.add(sendD3);
leftPane.add(parityLb3);
leftPane.add(sendD2);
// 创建右边面板
JPanel rightPane = new JPanel();
rightPane.setLayout(new GridLayout(3, 2));
// 设置右边面板各组件
JLabel baudrateLb = new JLabel("波特率:");
baudrateLb.setFont(lbFont);
baudrateLb.setHorizontalAlignment(SwingConstants.RIGHT);
rateCombox = new JComboBox(new Integer[] { 2400, 4800, 9600, 14400,
19200, 38400, 56000 });
rateCombox.setSelectedIndex(2);
rateCombox.addActionListener(this);
JLabel stopbitsLb = new JLabel("停止位:");
stopbitsLb.setFont(lbFont);
stopbitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
stopCombox = new JComboBox(new String[] { "1", "2", "1.5" });
stopCombox.addActionListener(this);
// JLabel stopbitsLb4 = new JLabel("DDDD:");
// stopbitsLb4.setFont(lbFont);
// stopbitsLb4.setHorizontalAlignment(SwingConstants.RIGHT);
// sendTf = new TextField(5);
openPortBtn = new Button("start");
openPortBtn.addActionListener(this);
closePortBtn = new Button("coles");
closePortBtn.addActionListener(this);
// 添加组件至面板
rightPane.add(baudrateLb);
rightPane.add(rateCombox);
rightPane.add(stopbitsLb);
rightPane.add(stopCombox);
// rightPane.add(stopbitsLb4);
// rightPane.add(sendTf);
rightPane.add(openPortBtn);
rightPane.add(closePortBtn);
// 将左右面板组合添加到北边的面板
northPane.add(leftPane);
northPane.add(rightPane);
JLabel stopbitsLbdd = new JLabel("地址端口:");
stopbitsLbdd.setFont(lbFont);
stopbitsLbdd.setHorizontalAlignment(SwingConstants.RIGHT);
// 创建中间面板
JPanel centerPane = new JPanel();
// 设置中间面板各组件
sendTf = new TextField(30);
readTa = new TextArea(8, 50);
readTa.setEditable(false);
readTa.setBackground(new Color(225, 242, 250));
centerPane.add(sendTf);
sendMsgBtn = new Button("send ");
sendMsgBtn.addActionListener(this);
JLabel stopbitsLbdd1 = new JLabel("地址:");
stopbitsLbdd1.setFont(lbFont);
stopbitsLbdd1.setHorizontalAlignment(SwingConstants.RIGHT);
sendTf1 = new TextField(20);
sendMsgBtn1 = new Button("send2 ");
sendMsgBtn1.addActionListener(this);
JLabel parityLb4 = new JLabel("命令:");
parityLb4.setFont(lbFont);
parityLb4.setHorizontalAlignment(SwingConstants.RIGHT);
parityCombox1 = new JComboBox(new String[] { "上传开关量", "上传SOE整定值",
"标志信息模拟量" });
parityCombox1.addActionListener(this);
// 添加组件至面板
centerPane.add(stopbitsLbdd);
centerPane.add(sendTf);
centerPane.add(sendMsgBtn);
centerPane.add(readTa);
centerPane.add(parityLb4);
centerPane.add(parityCombox1);
centerPane.add(stopbitsLbdd1);
centerPane.add(sendTf1);
centerPane.add(sendMsgBtn1);
// 设置南边组件
statusLb = new JLabel();
statusLb.setText(initStatus());
statusLb.setOpaque(true);
// 获取主窗体的容器,并将以上三面板以北、中、南的布局整合
JPanel contentPane = (JPanel) getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
contentPane.setOpaque(false);
contentPane.add(northPane, BorderLayout.NORTH);
contentPane.add(centerPane, BorderLayout.CENTER);
contentPane.add(statusLb, BorderLayout.SOUTH);
}
/**
* 初始化状态标签显示文本
*
* @return String
* @since 2012-3-23 上午12:01:53
*/
public String initStatus() {
portname = portCombox.getSelectedItem().toString();
rate = rateCombox.getSelectedItem().toString();
data = dataCombox.getSelectedItem().toString();
stop = stopCombox.getSelectedItem().toString();
parity = parityCombox.getSelectedItem().toString();
StringBuffer str = new StringBuffer("当前串口号:");
str.append(portname).append(" 波特率:");
str.append(rate).append(" 数据位:");
str.append(data).append(" 停止位:");
str.append(stop).append(" 校验位:");
str.append(parity);
return str.toString();
}
/**
* 扫描本机的所有COM端口
*
* @since 2012-3-23 上午12:02:42
*/
public void scanPorts() {
portList = new ArrayList<String>();
Enumeration<?> en = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId;
while (en.hasMoreElements()) {
portId = (CommPortIdentifier) en.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
String name = portId.getName();
if (!portList.contains(name)) {
portList.add(name);
}
}
}
if (null == portList || portList.isEmpty()) {
showErrMesgbox("未找到可用的串行端口号,程序无法启动!");
System.exit(0);
}
}
/**
* 打开串行端口
*
* @since 2012-3-23 上午12:03:07
*/
public void openSerialPort() {
// 获取要打开的端口
try {
portId = CommPortIdentifier.getPortIdentifier(portname);
} catch (NoSuchPortException e) {
showErrMesgbox("抱歉,没有找到" + portname + "串行端口号!");
setComponentsEnabled(true);
return;
}
// 打开端口
try {
serialPort = (SerialPort) portId.open("JavaRs232", 3927);
statusLb.setText(portname + "串口已经打开!");
} catch (PortInUseException e) {
showErrMesgbox(portname + "端口已被占用,请检查!");
setComponentsEnabled(true);
return;
}
// 打开端口的IO流管道
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
} catch (IOException e) {
showErrMesgbox(e.getMessage());
}
// 给端口添加监听器
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
showErrMesgbox(e.getMessage());
}
serialPort.notifyOnDataAvailable(true);
// 设置端口参数
try {
int rate = Integer.parseInt(this.rate);
int data = Integer.parseInt(this.data);
int stop = stopCombox.getSelectedIndex() + 1;
int parity = parityCombox.getSelectedIndex();
System.out.println("rate:" + rate);
System.out.println("data:" + data);
System.out.println("stop:" + stop);
System.out.println("parity:" + parity);
serialPort.setSerialPortParams(rate, data, stop, parity);
} catch (UnsupportedCommOperationException e) {
showErrMesgbox(e.getMessage());
}
}
/**
* 给串行端口发送数据
*
* @since 2012-3-23 上午12:05:00
*/
public void sendDataToSeriaPort(String mesg_info) {
byte[] sbuf = null;
String s_info = "";
sbuf = CRC16.getSendBuf(mesg_info);
s_info = CRC16.getBufHexStr(sbuf);
try {
sendCount++;
outputStream.write(hexStringToBytes(s_info));
outputStream.flush();
StringBuilder receivedMsg = new StringBuilder();
receivedMsg.append(receivedMsg)
.append("发送数据: " + mesg_info + " \n");
readTa.append(receivedMsg.toString());
} catch (IOException e) {
showErrMesgbox(e.getMessage());
System.out.println(mesg_info);
}
statusLb.setText(" 发送: " + sendCount
+ " 接收: " + reciveCount);
}
/**
* 关闭串行端口
*
* @since 2012-3-23 上午12:05:28
*/
public void closeSerialPort() {
try {
if (outputStream != null)
outputStream.close();
if (serialPort != null)
serialPort.close();
serialPort = null;
statusLb.setText(portname + "串口已经关闭!");
sendCount = 0;
reciveCount = 0;
sendTf.setText("");
sendTf1.setText("");
sendD1.setText("");
sendD2.setText("");
sendD3.setText("");
readTa.setText("");
} catch (Exception e) {
showErrMesgbox(e.getMessage());
}
}
/**
* 显示错误或警告信息
*
* @param msg
* 信息
* @since 2012-3-23 上午12:05:47
*/
public void showErrMesgbox(String msg) {
JOptionPane.showMessageDialog(this, msg);
}
/**
* 各组件行为事件监听
*/
public void actionPerformed(ActionEvent e) {
String msg_info = "";
if (e.getSource() == portCombox || e.getSource() == rateCombox
|| e.getSource() == dataCombox || e.getSource() == stopCombox
|| e.getSource() == parityCombox) {
statusLb.setText(initStatus());
}
if (e.getSource() == openPortBtn) {
setComponentsEnabled(false);
System.err.println("打开");
openSerialPort();
}
if (e.getSource() == closePortBtn) {
if (serialPort != null) {
closeSerialPort();
}
setComponentsEnabled(true);
}
if (e.getSource() == sendMsgBtn) {
if (serialPort == null) {
showErrMesgbox("请先打开串行端口!");
return;
}
mesg = sendTf.getText();
mesg_info_D1 = sendD1.getText();
mesg_info_D2 = sendD2.getText();
mesg_info_D3 = sendD3.getText();
String info_length = mesg + "" + mesg_info_D1 + "" + mesg_info_D2
+ "" + mesg_info_D3;
if (StrKit.isBlank(mesg) || StrKit.isBlank(mesg_info_D1)
|| StrKit.isBlank(mesg_info_D2)
|| StrKit.isBlank(mesg_info_D3)) {
showErrMesgbox("4个文本框必须填写完整!");
return;
} else {
boolean result = info_length.matches("[0-9]+");
if (result) {
msg_info = stringToHex16(mesg_info_D1, mesg_info_D2,
mesg_info_D3, mesg);
} else {
showErrMesgbox("输入内容中存在非法字符,内容只支持数字!");
return;
}
if (msg_info.length() < 12) {
showErrMesgbox("输入内容长度不够默认4个文本框总长度12位!");
return;
} else if (msg_info.length() > 12) {
showErrMesgbox("输入内容长度超限默认4个文本框总长度12位!");
return;
}
}
sendDataToSeriaPort(msg_info);
}
if (e.getSource() == sendMsgBtn1) {
String sc_info = "";
if (serialPort == null) {
showErrMesgbox("请先打开串行端口!");
return;
}
switch (parityCombox1.getSelectedIndex()) {
case 0:
sc_info = "0100000040";
break;
case 1:
sc_info = "030000000B";
break;
case 2:
sc_info = "0400000015";
break;
default:
break;
}
mesg1 = sendTf1.getText();
if (StrKit.isBlank(mesg1)) {
showErrMesgbox("请填写地址信息!");
return;
} else {
boolean result = mesg1.matches("[0-9]+");
if (result) {
if (Integer.parseInt(mesg1) > 255) {
showErrMesgbox("地址输入有误,1-255之间!");
return;
} else {
msg_info = stringToHex16(mesg1);
}
} else {
showErrMesgbox("输入内容中存在非法字符,内容只支持数字!");
return;
}
}
sendDataToSeriaPort(msg_info + "" + sc_info);
}
}
private String stringToHex16(String mesg12) {
String msg = "";
if (Integer.toString(Integer.parseInt(mesg12), 16).length() == 1) {
mesg12 = "0" + Integer.toString(Integer.parseInt(mesg12), 16);
} else {
mesg12 = Integer.toString(Integer.parseInt(mesg12), 16);
}
msg = mesg12;
return msg;
}
private String stringToHex16(String mesg_info_D1, String mesg_info_D2,
String mesg_info_D3, String mesg) {
String msg = "";
if (Integer.toString(Integer.parseInt(mesg_info_D1), 16).length() == 1) {
mesg_info_D1 = "0"
+ Integer.toString(Integer.parseInt(mesg_info_D1), 16);
} else {
mesg_info_D1 = Integer.toString(Integer.parseInt(mesg_info_D1), 16);
}
if (Integer.toString(Integer.parseInt(mesg_info_D3), 16).length() == 1) {
mesg_info_D3 = "0"
+ Integer.toString(Integer.parseInt(mesg_info_D3), 16);
} else {
mesg_info_D3 = Integer.toString(Integer.parseInt(mesg_info_D3), 16);
}
if (Integer.toString(Integer.parseInt(mesg_info_D2), 16).length() == 1) {
mesg_info_D2 = "000"
+ Integer.toString(Integer.parseInt(mesg_info_D2), 16);
} else if (Integer.toString(Integer.parseInt(mesg_info_D2), 16)
.length() == 2) {
mesg_info_D2 = "00"
+ Integer.toString(Integer.parseInt(mesg_info_D2), 16);
} else if (Integer.toString(Integer.parseInt(mesg_info_D2), 16)
.length() == 3) {
mesg_info_D2 = "0"
+ Integer.toString(Integer.parseInt(mesg_info_D2), 16);
} else {
mesg_info_D2 = Integer.toString(Integer.parseInt(mesg_info_D2), 16);
}
if (Integer.toString(Integer.parseInt(mesg), 16).length() == 1) {
mesg = "000" + Integer.toString(Integer.parseInt(mesg), 16);
} else if (Integer.toString(Integer.parseInt(mesg), 16).length() == 2) {
mesg = "00" + Integer.toString(Integer.parseInt(mesg), 16);
} else if (Integer.toString(Integer.parseInt(mesg), 16).length() == 3) {
mesg = "0" + Integer.toString(Integer.parseInt(mesg), 16);
} else {
mesg = Integer.toString(Integer.parseInt(mesg), 16);
}
msg = mesg_info_D1 + "" + mesg_info_D3 + "" + mesg + "" + mesg_info_D2;
return msg;
}
/**
* 端口事件监听
*/
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = null;
try {
Thread.sleep(30l);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
readBuffer = new byte[inputStream.available()];
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while (inputStream.available() > 0) {
inputStream.read(readBuffer);
}
System.out.println(byte2hex(readBuffer));
String msg = byte2hex(readBuffer).trim();
msg = msg.replaceAll(" ", "");
String v_info = Float16(msg.substring(10, 14) + ""
+ msg.substring(6, 10));
StringBuilder receivedMsg = new StringBuilder();
receivedMsg.append(receivedMsg).append(
"回复数据: " + v_info + "V\n");
readTa.append(receivedMsg.toString());
reciveCount++;
statusLb.setText(" 发送: " + sendCount
+ " 接收: "
+ reciveCount);
} catch (IOException e) {
}
}
}
/**
* 设置各组件的开关状态
*
* @param enabled
* 状态
* @since 2012-3-23 上午12:06:24
*/
public void setComponentsEnabled(boolean enabled) {
openPortBtn.setEnabled(enabled);
openPortBtn.setEnabled(enabled);
portCombox.setEnabled(enabled);
rateCombox.setEnabled(enabled);
dataCombox.setEnabled(enabled);
stopCombox.setEnabled(enabled);
parityCombox.setEnabled(enabled);
}
/**
* 运行主函数
*
* @param args
* @since 2012-3-23 上午12:06:45
*/
public static void main(String[] args) {
new JavaRs232();
}
public String readPort() {
byte[] readBuffer = new byte[50];
try {
while (inputStream.available() > 0) {
inputStream.read(readBuffer);
}
StringBuilder receivedMsg = new StringBuilder("/-- ");
receivedMsg.append(new String(readBuffer).trim()).append(" --/\n");
readTa.append(receivedMsg.toString());
reciveCount++;
statusLb.setText(" 发送: " + sendCount
+ " 接收: "
+ reciveCount);
} catch (IOException e) {
showErrMesgbox(e.getMessage());
}
return "";
}
private static String byte2hex(byte[] buffer) {
String h = "";
for (int i = 0; i < buffer.length; i++) {
String temp = Integer.toHexString(buffer[i] & 0xFF);
if (temp.length() == 1) {
temp = "0" + temp;
}
h = h + " " + temp;
}
return h;
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static String Float16(String msg) {
Float value = Float.intBitsToFloat(Integer.valueOf(msg.trim(), 16));
Float f = 0.15490197f;
return value + "";
}
}
CRC16算法:
package com.jetf.mm;
public class CRC16 {
static final String HEXES = "0123456789ABCDEF";
byte uchCRCHi = (byte) 0xFF;
byte uchCRCLo = (byte) 0xFF;
private static byte[] auchCRCHi = { 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
(byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
(byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
(byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
(byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
(byte) 0xC1, (byte) 0x81, (byte) 0x40 };
private static byte[] auchCRCLo = { (byte) 0x00, (byte) 0xC0, (byte) 0xC1,
(byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2,
(byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05,
(byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C,
(byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE,
(byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B,
(byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8,
(byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB,
(byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF,
(byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC,
(byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7,
(byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
(byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0,
(byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1,
(byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36,
(byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35,
(byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD,
(byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE,
(byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39,
(byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8,
(byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A,
(byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF,
(byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4,
(byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
(byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3,
(byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0,
(byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63,
(byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6,
(byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64,
(byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D,
(byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA,
(byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9,
(byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9,
(byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA,
(byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D,
(byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
(byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6,
(byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73,
(byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50,
(byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53,
(byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57,
(byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54,
(byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F,
(byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A,
(byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58,
(byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89,
(byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E,
(byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
(byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85,
(byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86,
(byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41,
(byte) 0x81, (byte) 0x80, (byte) 0x40 };
public int value;
public CRC16() {
value = 0;
}
public void update(byte[] puchMsg, int usDataLen) {
int uIndex; // int i = 0;
for (int i = 0; i < usDataLen; i++) {
uIndex = (uchCRCHi ^ puchMsg[i]) & 0xff;
uchCRCHi = (byte) (uchCRCLo ^ auchCRCHi[uIndex]);
uchCRCLo = auchCRCLo[uIndex];
}
value = ((((int) uchCRCHi) << 8 | (((int) uchCRCLo) & 0xff))) & 0xffff;
return;
}
public void reset() {
value = 0;
uchCRCHi = (byte) 0xff;
uchCRCLo = (byte) 0xff;
}
public int getValue() {
return value;
}
private static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
private static byte[] HexString2Buf(String src) {
int len = src.length();
byte[] ret = new byte[len / 2 + 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < len; i += 2) {
ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
}
return ret;
}
public static byte[] getSendBuf(String toSend) {
byte[] bb = HexString2Buf(toSend);
CRC16 crc16 = new CRC16();
crc16.update(bb, bb.length - 2);
int ri = crc16.getValue();
bb[bb.length - 1] = (byte) (0xff & ri);
bb[bb.length - 2] = (byte) ((0xff00 & ri) >> 8);
return bb;
}
public static boolean checkBuf(byte[] bb) {
CRC16 crc16 = new CRC16();
crc16.update(bb, bb.length - 2);
int ri = crc16.getValue();
if (bb[bb.length - 1] == (byte) (ri & 0xff)
&& bb[bb.length - 2] == (byte) ((0xff00 & ri) >> 8))
return true;
return false;
}
public static String getBufHexStr(byte[] raw) {
if (raw == null) {
return null;
}
final StringBuilder hex = new StringBuilder(2 * raw.length);
for (final byte b : raw) {
hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(
HEXES.charAt((b & 0x0F)));
}
return hex.toString().toLowerCase();
}
/****
* * 得到CRC验证 } } } } } }
*
* @param tt
* * @return
*/
public static String getCrc(String tem) { // String tem=""; // for(int
// i=0;i<tt.length;i++){ //
// tem+=tt[i]; //
// System.out.println("这是传入的值"+tt[i]);
// // }
byte[] sbuf = CRC16.getSendBuf(tem);
System.out.println("这是得到的crc" + CRC16.getBufHexStr(sbuf));
return CRC16.getBufHexStr(sbuf).substring(12, 16).toLowerCase();
}
/** 得到要发送的数据 * @param args */
public static String getSendData(String[] tt) {
String tem = "";
for (int i = 0; i < tt.length; i++) {
tem += tt[i];
}
byte[] sbuf = CRC16.getSendBuf(tem);
return CRC16.getBufHexStr(sbuf);
}
public static byte[] getSendBuf2(String[] tt) {
String tem = "";
for (int i = 0; i < tt.length; i++) {
tem += tt[i];
}
byte[] bb = HexString2Buf(tem);
CRC16 crc16 = new CRC16();
crc16.update(bb, bb.length - 2);
int ri = crc16.getValue();
bb[bb.length - 1] = (byte) (0xff & ri);
bb[bb.length - 2] = (byte) ((0xff00 & ri) >> 8);
return bb;
}
public static void main(String[] args) { // TODO Auto-generated method stub
// //0103040a3d3fb739a1----sendB
// //010304b8523ffeef32----sendB
String ms = "";
byte[] sbuf = CRC16.getSendBuf("010400000015");
System.out.println(CRC16.getBufHexStr(sbuf));
}
}
Float16算法:
package com.jetf.mm;
public class Float16 {
@SuppressWarnings("unused")
public static void main(String[] args) {
String s = "057e";
Float value = Float.intBitsToFloat(Integer.valueOf(s.trim(), 16));
// Double
System.out.println(Integer.valueOf(s.trim(), 16));
Float f = 225.92f;
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}
还没有评论,来说两句吧...