counting 1 bits SPOILER
来源:互联网 发布:阿里云企业备案 编辑:程序博客网 时间:2024/05/17 18:45
counting 1 bits SPOILER
This spoiler/nodeshell rescue is in reference to Ariels's writeup in "counting 1 bits."
Sick of staring at that ampersand? Bitter at binary? Let's start by reviewing the given code.
for( n = 0; b; n++ )b &= (b - 1);
What we've got here is a loop that counts the number of "1" bits in a given number b. After this loop runs, b will equal zero and n will equal the number of 1 bits in b. The tricky part of that loop is the bitwise AND operator, the &=. Given two numbers, a bitwise AND will examine each bit in each number and set the corresponding bit in a result to 1 if both bits in the given numbers were 1; or in any other case 0. If you're not already familiar with this, you really ought to read Wharfinger's writeup for bitwise.
So how does it work? Let us unroll that loop! Set b equal to 45 (0010 1101) and let 'er rip.
n b 1 0010 11012 0010 11003 0010 10004 0010 0000 0000 0000 (loop stops)
And so the loop runs four times, clearing the lowest bit each time through. Still not getting it? Look at (b-1) in comparison to b.
9: 0000 1001 27: 0001 10118: 0000 1000 26: 0001 1010 42: 0010 1010 116: 0111 010041: 0010 1001 115: 0111 0011
What's going on here? When you subtract 1 from a binary number, you're really turning off the rightmost 1 and turning on every bit after it. Toggling them all, if you will. Let's explicate the loop again. This time, pay close attention to what happens when we logically AND the two numbers together.
n b0 0010 1101-------------- 0010 1101 & 0010 1100 = 0010 11001-------------- 0010 1100 & 0010 1011 = 0010 10002-------------- 0010 1000 & 0010 0111 = 0010 00003-------------- 0010 0000 & 0001 1111 = 0000 00004--------------
Each iteration through the loop, everything from the least significant 1 bit to the least significant bit is ANDed with its inverse, setting them and every bit betwixt the two to zero. Since the loop eats precisely one bit at a time, it will run until all of the bits have been turned to zeros, leaving n equal to the number of times the loop was processed, and thus counting the 1 bits in that given number b.
No nibbles were harmed during the creation of this spoiler.- counting 1 bits SPOILER
- Counting 1-bits
- counting 1 bits C implementations
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- 最近几个报告会介绍[原文写作时间:2006年7月12日]
- Computer Magazine : Total 2004 Collection
- 谈谈C#中的接口
- HTML常用代码
- 距离开学还有1个月时间
- counting 1 bits SPOILER
- Spring中Bean配置参数说明
- 几小段代码
- javascript如何操作框架页中的域
- oracle数据安全面面观
- javascript如何取得任意两时间的差
- C#对XML文件的操作
- .NET中如何引入外部的程序
- C#学习笔记