int b=(a<<6)+(a<<5)+(a<<2);//умножить на 100 int c=(a<<10)-((a<<4)+(a<<3));//умножить на 1000 int d=(a<<3)+(a<<1);//умножить на 10 

Tell me how to divide by 10,100,1000 any number of 'a' with an offset (shift)? Integer int (the remainder of the division is not important).

  • five
    If this is for optimization purposes, then in vain, just write a/100 , the compiler will do everything in the best way. - Vladimir Gamalyan
  • The compiler is sometimes a stupid animal. I want to understand for myself whether there is a way to divide by shift. - Alex Bigalo
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Easily :)

0.1 10 = 0.0001100110011001 2 . That is, the division by 10 is 1/16 + 1/32 + 1/256 + 1/512 + ...

Further explain? :)

But seriously - take Warren’s book Algorithmic Tricks for Programmers, there is Chapter 10, The Whole Division into Constants. There are many standing.

The same division by 10:

 unsigned divu10(unsigned n) { unsigned q, r; q = (n >> 1) + (n >> 2); q = q + (q >> 4); q = q + (q >> 8); q = q + (q >> 16); q = q >> 3; r = n - q * 10; return q + ((r + 6) >> 4); // return q + (r > 9); } 
  • Is it easier? I am trying to translate asm in the move mov eax, edi mov edx, 1717986919 sar edi, 31 imul edx sar edx, 2 mov eax, edx sub eax, edi ret You have longer. - pavel
  • Multiplication also needs to be implemented on shifts, otherwise the meaning is lost. "r = n - ((q << 1) + (q << 3));" For a hint where to read a big thank you. Then I will try to figure it out myself. - Alex Bigalo
  • @AlexBigalo You have already demonstrated multiplication by 10 through shifts in your question; what's the problem? ... - Harry