比较两个字节数组?(爪哇)

Compare two Byte Arrays? (Java)(比较两个字节数组?(爪哇))
本文介绍了比较两个字节数组?(爪哇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个字节数组,里面有一个~已知的二进制序列.我需要确认二进制序列是它应该是什么.除了 == 之外,我还尝试了 .equals,但都没有成功.

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

推荐答案

在你的例子中,你有:

if (new BigInteger("1111000011110001", 2).toByteArray() == array)

在处理对象时,java中的==会比较引用值.您正在检查 toByteArray() 返回的对数组的引用是否与 array 中保存的引用相同,这当然不可能是真的.此外,数组类不会覆盖 .equals() 因此其行为是 Object.equals() 的行为,它也只比较参考值.

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.

为了比较两个数组的内容,数组类

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?)
Convert integer to zero-padded binary string(将整数转换为零填充的二进制字符串)
How Can I Convert Very Large Decimal Numbers to Binary In Java(如何在 Java 中将非常大的十进制数转换为二进制数)
Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
Embed a Executable Binary in a shell script(在 shell 脚本中嵌入可执行二进制文件)
why does quot;STRINGquot;.getBytes() work different according to the Operation System(为什么“STRING.getBytes() 的工作方式因操作系统而异)