Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to use bit shifts to perform division by 10 is to multiply the number by a suitable factor before the division, such that the quotient and remainder can be calculated using only bitwise operations. For example, to divide an unsigned 32-bit integer x by 10, we can first multiply it by a constant factor 0x1999999A (i.e. (2^32)/10), which can be computed offline and stored in a lookup table or computed at runtime using shifts and additions:

unsigned int factor = 0x1999999A;

unsigned int q = (x * factor) >> 32; // quotient unsigned int r = x - q * 10; // remainder

The quotient can be obtained by right-shifting the product of x and the factor by 32 bits (i.e. discarding the lower 32 bits), which effectively divides the product by 2^32. The remainder can then be computed by subtracting the product of the quotient and 10 from x. This approach avoids the use of costly division instructions and can be faster than other division methods for some architectures. However, it may not be as accurate as true division for large numbers, and care must be taken to handle overflow and rounding errors.