简体   繁体   English

在字节数组中查找特定字符?

[英]Find specific characters in byte array?

I am connecting to a terminal emulator using a library in android, this connects to a serial device (a switch) and shows me sent/received data. 我正在使用android中的库连接到终端仿真器,这连接到串行设备(交换机)并向我显示发送/接收的数据。

However I am just sending byte arrays over and back so I don't know what status the switch is in, is it in enable more or configuration mode etc. This leads me to possibly enter commands in the wrong mode and they won't work. 但是我只是来回发送字节数组,所以我不知道开关处于什么状态,它处于启用更多状态还是配置模式等。这导致我可能以错误的模式输入命令,它们将无法工作。 The switch is then in an unrecoverable mode as I have sent a wrong command and there is no way to delete it or get to a new line. 然后,交换机处于不可恢复的模式,因为我发送了错误的命令,无法删除它或进入新行。 The problem I am trying to deal with for now is the one where I don;t know the mode the switch is in. I know that I can have three different return prompts after I send a command: 我现在要解决的问题是我不知道的问题;我不知道开关所处的模式。我知道在发送命令后可以有三种不同的返回提示:

switch>
switch#
switch(config)#

So I was thinking that if I read the last two characters received I could tell which mode I'm in. h>, h# and )# 所以我在想,如果我阅读收到的最后两个字符,我就能知道我处于哪种模式。h>,h#和)#

I get data back in this method, whenever data is received this is run: 我通过这种方法获取数据,每当接收到数据时就运行它:

public void onDataReceived(int id, byte[] data) 
{

    String str = new String(data);
    ((MyBAIsWrapper) bis).renew(data);

    mSession.write(str);
    mSession.notifyUpdate();
    viewHandler.post(updateView);
}

Would the best way to do this be search the byte array somehow or to convert it to a string and search the string for h>, h# and )#, then I could set a global variable depending on the value I get back? 做到这一点的最佳方法是以某种方式搜索字节数组或将其转换为字符串并在字符串中搜索h>,h#和)#,然后我可以根据获取的值设置全局变量? Maybe search from the end backwards? 也许从头到尾搜索?

I would search the byte[] and avoid the overhead from the conversion to a String . 我将搜索byte[]并避免从转换为String产生的开销。

If it is more performant to start search from the end, depends on the data you get. 如果从头开始搜索更有效,则取决于获得的数据。 I cannot judge this by the little example you posted in your question. 我无法通过您在问题中发布的小例子来判断这一点。

If you only need to look at the last two characters: 如果只需要查看最后两个字符:

if(data[data.length-2]=='h' && data[data.length-1]=='>') // "h>"


if(data[data.length-2]=='h' && data[data.length-1]=='#') // "h#"

Or if it is not so simple, use a loop to iterate the array. 或者,如果不是那么简单,则使用循环来迭代数组。

Ps I assumes ASCII encoding for the code above PS我假设上面代码的ASCII编码

Do you mean? 你的意思是?

if(str.endsWith("h>") || str.endsWith("h#") || str.endsWith(")#"))

or simpler 或更简单

if(str.equals("switch>") || str.equals("switch#") || str.equals("switch(context)#"))

or using a regex 或使用正则表达式

final Pattern switched = Pattern.compile("switch(>|#|\\(\\w+\\)#)");

if(str.matcher(switched).matches())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM