比较两个字节数组? (Java)

我有一个字节数组,其中包含一个已知的二进制序列。我需要确认二进制序列是否正确。除了 ==之外,我还试过 .equals,但都不管用。

byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
if (new BigInteger("1111000011110001", 2).toByteArray() == array){
System.out.println("the same");
} else {
System.out.println("different'");
}
119208 次浏览

Check out the static java.util.Arrays.equals() family of methods. There's one that does exactly what you want.

Java doesn't overload operators, so you'll usually need a method for non-basic types. Try the Arrays.equals() method.

In your example, you have:

if (new BigInteger("1111000011110001", 2).toByteArray() == array)

When dealing with objects, == in java compares reference values. You're checking to see if the reference to the array returned by toByteArray() is the same as the reference held in array, which of course can never be true. In addition, array classes don't override .equals() so the behavior is that of Object.equals() which also only compares the reference values.

To compare the contents of two arrays, static array comparison methods are provided by the Arrays class

byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
if (Arrays.equals(array, secondArray))
{
System.out.println("Yup, they're the same!");
}

Of course, the accepted answer of Arrays.equal( byte[] first, byte[] second ) is correct. I like to work at a lower level, but I was unable to find a low level efficient function to perform equality test ranges. I had to whip up my own, if anyone needs it:

public static boolean ArraysAreEquals(
byte[] first,
int firstOffset,
int firstLength,
byte[] second,
int secondOffset,
int secondLength
) {
if( firstLength != secondLength ) {
return false;
}


for( int index = 0; index < firstLength; ++index ) {
if( first[firstOffset+index] != second[secondOffset+index]) {
return false;
}
}


return true;
}

You can use both Arrays.equals() and MessageDigest.isEqual(). These two methods have some differences though.

MessageDigest.isEqual() is a time-constant comparison method and Arrays.equals() is non time-constant and it may bring some security issues if you use it in a security application.

The details for the difference can be read at Arrays.equals() vs MessageDigest.isEqual()

Since I wanted to compare two arrays for a unit Test and I arrived on this answer I thought I could share.

You can also do it with:

@Test
public void testTwoArrays() {
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();


Assert.assertArrayEquals(array, secondArray);
}

And you could check on Comparing arrays in JUnit assertions for more infos.