我试图从串口读取一个双。 我可以在String中读取它,但是当我将String解析为Double时,结果没有意义,并且它与String不一样。
这是我的代码:
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
String peso = new String (readBuffer, 0, numBytes, "UTF-8");
System.out.print(new String (readBuffer, 0, numBytes, "UTF-8"));
//double d = ByteBuffer.wrap(readBuffer).order(ByteOrder.LITTLE_ENDIAN ).getDouble();
//System.out.print(d);
m_dWeightBuffer = Double.parseDouble(peso);
System.out.print(m_dWeightBuffer);
}
//System.out.print(new String (readBuffer, 0, numBytes, "UTF-8"));
} catch (IOException ex) {}
break;
}
}
但现在,您知道如何将此字符串转换为Double?
System.out.print(new String (readBuffer, 0, numBytes, "UTF-8"));
输出:000.250
好
m_dWeightBuffer = Double.parseDouble(peso);
System.out.print(m_dWeightBuffer);
输出:0.00.0250.0
错误
System.out.println(new String (readBuffer, 0, numBytes, "UTF-8"));
输出:
0
0
0
.250
答案 0 :(得分:3)
服务器似乎正在串行端口上写入4个块,可能是64位字:
你正在读取64位的最大缓冲区(readBuffer.length * 8位),所以最后一个可能是:
0011111111010000000000000000000000000000000000000000000000000000
试一试:
String s = "0011111111010000000000000000000000000000000000000000000000000000";
double d = Double.longBitsToDouble(Long.parseLong(s,2));
System.out.println(d); //-> 0.25
至于现在没有错误。
可能你想要在一个点上处理所有4个块,所以你可以尝试以下 - 当然,很大程度上取决于我忽略的协议的语义:
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
String peso = "";
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
peso += new String (readBuffer, 0, numBytes, "UTF-8");
}
m_dWeightBuffer = Double.parseDouble(peso);
} catch (IOException ex) {}
break;
}
}
也就是说,在读取所有数据后创建double。
答案 1 :(得分:2)
尝试这样做:
public void serialEvent(SerialPortEvent event){
switch(event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
peso += new String (readBuffer, 0, numBytes, "UTF-8").replaceAll("\\s+","").replaceAll("\\n", "").replaceAll("\\r", "");
}
} catch (IOException ex) {}
break;
}
}
Inicialize此SerialEvent方法的String peso OUTSIDE。