Zaphod
Zaphod

Reputation: 1417

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

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

Upvotes: 5

Views: 5187

Answers (3)

elm
elm

Reputation: 20415

Consider also the difference between a1 and a2,

(a1 diff a2).isEmpty

which halts the comparing at the first mismatch.

Upvotes: 4

marios
marios

Reputation: 8996

 val arrayOne = Array(1,2,3)
 val arrayTwo = Array(1,2,3)

 arrayOne zip arrayTwo forall {case (a,b) => a == b}

Upvotes: 2

Eugene Ryzhikov
Eugene Ryzhikov

Reputation: 17359

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)

Upvotes: 19

Related Questions