• Post Reply Bookmark Topic Watch Topic
  • New Topic

comparing byte array contents  RSS feed

 
Alessandro Brawerman
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I'd like to know how to compare the contents of 2 byte arrays.
I have tried the following:

byte[] data = "test".getBytes();
byte[] data2 = "test".getBytes();
if(data2.equals(data)) System.out.println("YES");
else System.out.println("NO");

It didn't work, I thought that using .equals would work, but no.
Thanks,
Alessandro.
 
Sherry Nelson
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think using java.util.Arrays() with both arrays passed as parameters should work.

cheers,
Sherry
 
Sherry Nelson
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops, I meant
java.util.Arrays.equals(byte[] , byte[] )
 
Alessandro Brawerman
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sherry, comparing the byte arrays with the Arrays.equals worked.
Just one more question. In the code below result and original are still different, is there something that you think is wrong or missing?

Cipher cipher1 = Cipher.getInstance("AES", "BC");
Cipher cipher2 = Cipher.getInstance("AES", "BC");
cipher1.init(Cipher.ENCRYPT_MODE, key);
cipher2.init(Cipher.DECRYPT_MODE, key);
byte[] data = "test".getBytes();
byte[] result = cipher1.doFinal("test".getBytes());
byte[] original = cipher2.doFinal(result);

if(Arrays.equals(result, original)) System.out.println("YES");
else System.out.println("NO");
 
Alessandro Brawerman
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never mind. I was comparing the wrong arrays.
It should be:
if(Arrays.equals(data, original))
and not:
if(Arrays.equals(result, original))

Sorry.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!