[英]Equivalent of strcmp() in Java for comparing byte arrays
I use a byte array to fit 1024 bytes. 我使用字节数组来容纳1024个字节。 The problem is, at separate times in my code I need to only use SOME of those bits. 问题是,在我的代码中的不同时间,我只需要使用其中一些位。 In C, I have used... 在C语言中,我使用过...
byte buff[] = read();
strcmp( buff, "CMD\r\n" );
This would ignore all later bytes in the array, and only compare the first 5 bytes. 这将忽略数组中的所有后续字节,仅比较前5个字节。 Is there an easy way to do this in Java? 有没有简单的方法可以在Java中做到这一点?
You can compare an array of bytes with Arrays.equals( byte[], byte[] ) . 您可以将一个字节数组与Arrays.equals(byte [],byte [])比较 。
byte[] buff = ...;
boolean isEqual = Arrays.equals( buff,
"CMD\r\n".getBytes( Charset.forName( "US-ASCII" )));
EDIT : I missed that your byte array is 1024 bytes. 编辑 :我错过了您的字节数组是1024字节。
One option is to compare a slice of the byte array: 一种选择是比较字节数组的一部分:
byte[] buff = ...;
final byte[] CMD_BYTES = "CMD\r\n".getBytes( Charset.forName( "US-ASCII" ));
boolean isEqual = Arrays.equals( Arrays.copyOf( buff, CND_BYTES.length()),
CMD_BYTES );
Another option is to convert the byte array up to a String, allowing an expression similar to C++. 另一种选择是将字节数组转换为字符串,从而允许类似于C ++的表达式。
byte[] buff = ...;
int buffLen = ...;
String command = new String( buff, 0, buffLen, Charset.forName("US-ASCII"));
int cmp = command.compareTo( "CMD\r\n");
Well it's trivial to write it yourself: 好吧,自己编写它很简单:
public static boolean truncatedEquals(byte[] x, byte[] y) {
int upperBound = Math.min(x.length, y.length);
for (int i = 0; i < upperBound; i++) {
if (x[i] != y[i]) {
return false;
}
}
return true;
}
I don't believe there's anything built into Java for this. 我不相信Java有任何内置功能。
Note that I've made the input two byte[]
- bytes and strings are very different, and should be treated differently. 请注意,我将输入设为两个byte[]
-字节和字符串非常不同,因此应区别对待。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.