Hi All, This is probably a very basic question, but I'm looking for an efficent way to compare two byte arrays. Lets say you have some code like the following:
boolean compare_byte_array(byte[] b1, byte[] b2) { if (b1.length != b2.length) { return false; } for (int i=0; i < b1.length; i++) { if (b1 != b2) { return false; } } return true; }
Surley there must be a more efficent way of implementing this? Is there a way to do a memory comparison - if I were implementing this in c++ I'd use memcmp() in place of that for loop.
BTW would the following do the trick - boolean compare_byte_array(byte[] b1, byte[] b2) { return (b1 == b2); }
what exactly gets compared here - does this do a deep comparison of each element? or does this simply check that b1 and b2 are indeed the same obects.
take a look at java.util.Arrays.equals (byte[] b, byte[] b2)
... it compares two arrays of byte. I don't know how efficient is this method, wether it loops over the two arrays and compares each correspondig elements (wich is indeed a not so efficient implementation) or does some internal memory comparison ...