1

我喜欢看到人们编写 Bit Twiddling 代码,但我根本无法理解。通过 Hacker's Delight 和http://graphics.stanford.edu/~seander/bithacks.html,但我什么都不懂。

例如:

如何1 | 2返回3或如何a ^=b; b ^= a; a ^=b;交换值等......

一种方法:

private T[] ensureCapacity(int minCapacity) {
   if (tmp.length < minCapacity) {
   // Compute smallest power of 2 > minCapacity
   newSize |= newSize >> 1;
   int newSize = minCapacity;
   newSize |= newSize >> 2;
   newSize |= newSize >> 4;
   newSize |= newSize >> 8;
   newSize |= newSize >> 16;
   newSize++;

    if (newSize < 0) // Not bloody likely!
      newSize = minCapacity;
    else
      newSize = Math.min(newSize, a.length >>> 1);

      @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
      T[] newArray = (T[]) new Object[newSize];
      tmp = newArray;
   }
   return tmp;
 }

以下喜欢的人在做什么:

int newSize = minCapacity;
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
newSize++;

或者

newSize = Math.min(newSize, a.length >>> 1);

更好地使用>>or>>>运算符我的意思是在 Joshua Bloch 修复了损坏的二进制搜索之后,我明白使用它是安全>>>>>。请帮助,如果有教程,那么上面提到的来源我将非常感激。

例如,计算位输出的最简单方法是什么1 | 2 = 3

我的意思是我不知道位形式的外观,除非我使用计算器或其他东西。有没有最简单的方法可以在没有任何帮助的情况下计算这些东西?

4

2 回答 2

1

计算位输出的最简单方法是什么,例如 1 | 2 = 3。

把数字写成二进制。这就是数字的真实表示方式。

  00000001
| 00000010
= 00000011
于 2013-05-14T17:31:07.563 回答
1

You're gonna have to study a little, but here's a little cheat sheet to know the number in binary form

128 | 64 | 32 | 16 | 8 | 4 | 2 | 1

If you want 3, go from left to right, filling up in the spaces that contains the values you need to create the number 3

128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
                             X   X

2 + 1 = 3 so you replace the ones marked with X with 1s and the rest with 0s

00000011

The same for the number 2:

128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
                             X

And the binary result is.

00000010

For the number 47:

128 | 64 | 32 | 16 | 8 | 4 | 2 | 1
            X        X   X   X   X

Binary result:

00101111

This is not a rule, or formula or anything. It's just something to help you convert numbers a little faster, and practice it in your head. You'll still need to study a lot if you want to play with bits :-)

于 2013-05-14T17:35:22.260 回答