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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-06-25 11:00:00 +0000
Seen: 8 times
Last updated: Jun 26 '21