Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the consecutive zero bits (trailing) on the right in parallel: an explanation?

Consider this link from the Bit Twiddling Hacks website. In order to count the trailing bits, the following algorithm is used:

unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v); /* THIS LINE */
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;

Can someone explain me the role of the line marked as /* THIS LINE */ and more importantly is it possible to use only bitwise operations to avoid the use of signed() ?

EDIT: How to replace signed() by arithmetic/logical/bitwise operations?

like image 262
Vincent Avatar asked Jan 23 '14 04:01

Vincent


People also ask

How do you find the number of trailing zeros in binary representation?

Given an integer, count the number of trailing zeroes. For example, for n = 12, its binary representation is 1100 and number of trailing zero bits is 2. Examples : Input : 8 Output : 3 Binary of 8 is 1000, so there are three trailing zero bits.

What is trailing zeros in binary number?

The position of zeros after first one from the least significant bit (LSB) is called as trailing zeros in binary number.

What is XOR bit operation?

A bitwise XOR is a binary operation that takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only one of the bits is 1, but will be 0 if both are 0 or both are 1.

How do you set a specific bit to zero?

Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.


1 Answers

v &= -signed(v) will clear all but the lowest set bit (1-bit) of v, i.e. extracts the least significant 1 bit from v (v will become a number with power of 2 afterwards). For example, for v=14 (1110), after this, we have v=2 (0010).

Here, using signed() is because v is unsigned and you're trying to negate an unsigned value (gives compilation error with VS2012) (comment from JoelRondeau). Or you will get a warning like this: warning C4146: unary minus operator applied to unsigned type, result still unsigned (my test).

like image 108
herohuyongtao Avatar answered Sep 30 '22 11:09

herohuyongtao