Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Byte[]'s for equality in Scala (checking binary image data)

Tags:

scala

I want to compare two (small) Byte[]'s that contain a representation of a binary image. I don't want to use MD5 or SHA or whatnot because there is no point... these just iterate the array, calculate a checksum, etc., and there is no need.

It seems there should be a super-easy way to iterate of two arrays, a1 and a2, and compare them for equality, such as:

(a1, a2).forall(a, b => a == b)

But this does not work of course...

like image 655
Zaphod Avatar asked Jun 09 '15 22:06

Zaphod


People also ask

How do you know if two byte arrays are equal?

equals(byte[] a, byte[] a2) method returns true if the two specified arrays of bytes are equal to one another. Two arrays are equal if they contain the same elements in the same order. Two array references are considered equal if both are null.

How do you compare two bytes?

The 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.

How do I print a byte array?

You can simply iterate the byte array and print the byte using System. out. println() method.


2 Answers

Following should do it

val a: Array[Byte] = Array(1,2,4,5)
val b: Array[Byte] = Array(1,2,4,5)
a.deep==b.deep 

The other way would be

a.sameElements(b)
like image 79
Eugene Ryzhikov Avatar answered Sep 30 '22 18:09

Eugene Ryzhikov


Consider also the difference between a1 and a2,

(a1 diff a2).isEmpty

which halts the comparing at the first mismatch.

like image 23
elm Avatar answered Sep 30 '22 18:09

elm