比较两个字节数组? (JAVA) [英] Compare two Byte Arrays? (Java)

查看:162
本文介绍了比较两个字节数组? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它了〜称为二进制序列的字节数组。我需要确认二进制序列是它的应该是。我曾尝试 .equals 除了 == ,但既不工作。

  byte []数组=新的BigInteger(1111000011110001,2).toByteArray();
如果(新的BigInteger(1111000011110001,2).toByteArray()==阵列){
    的System.out.println(相同的);
}其他{
    的System.out.println(不同的');
}


解决方案

在你的榜样,你有:

 如果(新的BigInteger(1111000011110001,2).toByteArray()==数组)

当有物体在Java中处理, == 比较的参考值的。你检查,看看是否参考了 toByteArray()返回的数组是相同阵列,这当然可以永远不会为真。此外,数组类不重写 .equals()这样的行为是的Object.Equals()这也只比较的参考值。

要比较两个阵列,通过的内容的=htt​​p://docs.oracle.com/javase/7/docs/api/java /util/Arrays.html\">Arrays类

  byte []数组=新的BigInteger(1111000011110001,2).toByteArray();
字节[] secondArray =新的BigInteger(1111000011110001,2).toByteArray();
如果(满足Arrays.equals(数组,secondArray))
{
    的System.out.println(是啊,他们是一样的!);
}

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'");
}

解决方案

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!");
}

这篇关于比较两个字节数组? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆