简体   繁体   English

如何添加两个BitSet

[英]How to add two BitSet

I am looking for a way to add two BitSet. 我正在寻找一种添加两个BitSet的方法。 Should i go to the basics of binary number and perform XOR and AND operation over BitSet. 我应该去了解二进制数的基础知识,然后对BitSet进行XORAND操作。 As basic says here- 就像这里基本说的 半加法器

Will this be efficient? 这会有效吗?

No, it wouldn't be efficient, because you wouldn't know the carry for bit N until you've processed all bits through N-1 . 不,这没有效率,因为在处理完N-1所有位之前,您不会知道N位的进位。 This is the problem solved by carry look-ahead adders in hardware. 这是通过硬件中的进位超前加法器解决的问题。

There is no way to implement addition of BitSets in a way that does not involve examining all their bits one-by-one in the worst case. 没有一种方法可以实现在最坏的情况下不逐位检查所有位的方式来实现BitSet的添加。 An alternative strategy depends a lot on your specific requirements: if you mutate your bit sets a lot, you may want to roll your own, based on Sun's Oracle's implementation. 替代策略在很大程度上取决于您的特定要求:如果您对位集进行大量更改,则可能需要根据 Sun的 Oracle实施来自己动手。 You can shamelessly copy borrow their code, and add an implementation of add that operates on the "guts" of the BitSet , stored as long[] bits . 您可以 毫不客气地复制 借用他们的代码,并添加对以long[] bits存储的BitSet的“内容”进行操作的add实现。 You'll need to be very careful dealing with overflows (remember, all numbers in Java are signed), but otherwise it should be rather straightforward. 您需要非常小心地处理溢出(记住,Java中的所有数字都是带符号的),但是否则应该很简单。

最有效的方法是将两个位集都转换为数字,然后将它们相加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM