Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Byte Arrays? (Java)

Tags:

java

binary

I have a byte array with a ~known binary sequence in it. I need to confirm that the binary sequence is what it's supposed to be. I have tried .equals in addition to ==, but neither worked.

byte[] array = new BigInteger("1111000011110001", 2).toByteArray(); if (new BigInteger("1111000011110001", 2).toByteArray() == array){     System.out.println("the same"); } else {     System.out.println("different'"); } 
like image 736
Roger Avatar asked Mar 26 '11 02:03

Roger


People also ask

How to compare 2 byte arrays Java?

To compare two-byte arrays, Java has a built-in method Arrays. equal(). It checks for the equality of two arrays.

How do you compare two bytes?

Byte compare() method in Java with examplesThe compare() method of Byte class is a built in method in Java which is used to compare two byte values. Parameters: It takes two byte value 'a' and 'b' as input in the parameters which are to be compared. Return Value: It returns an int value.

Can you compare byte and int in Java?

In java automatic type conversion converts any small data type to the larger of the two types. So byte b is converted to int b when you are comparing it with int a . Do know that double is the largest data type while byte is the smallest.


2 Answers

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!"); } 
like image 190
Brian Roach Avatar answered Sep 20 '22 08:09

Brian Roach


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

like image 37
Ernest Friedman-Hill Avatar answered Sep 20 '22 08:09

Ernest Friedman-Hill