0

Suppose, we have some 970 number in eax I tried this to calculate number of digits

mov ebx, 10
mov ecx, 0
labelDivider: 
inc ecx
cdq
idiv ebx
cmp eax, 0
jnz labelDivider

The result value should be placed in ecx and at a result I have 1 all the time - not 3 or another (If I change initial number).

Jester
  • 56,577
  • 4
  • 81
  • 125
mkip
  • 71
  • 1
  • 2
  • 11
  • 2
    The code as shown **does** produce `3` in `ecx` correctly. – Jester Apr 21 '21 at 18:17
  • 1
    Try single stepping in your debugger to see what it is doing. – Erik Eidt Apr 21 '21 at 18:18
  • 1
    It works fine for me. The bug might be in some other part of your code. Please post a [mcve]. – Nate Eldredge Apr 21 '21 at 19:26
  • It would be much faster to multiply by 10 (starting with 1) and `cmp eax, ecx` / `jae .loop` than to divide the original number, if you don't actually need the decimal digits. But if you do, save them along the way so you can just copy them to wherever you eventually want them, at the same time as figuring out how many there are. [How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894) – Peter Cordes Apr 21 '21 at 20:21

1 Answers1

2

If you want to avoid division, which is slow on old processors, another approach is possible, assuming the input number in EAX is an unsigned integer:

   MOV ECX,1
   CMP EAX,9
   JNA Done
   INC ECX
   CMP EAX,99
   JNA Done
   INC ECX
   CMP EAX,999
   JNA Done
   INC ECX
   CMP EAX,9999
   JNA Done
   INC ECX
   CMP EAX,99999
   JNA Done
   INC ECX
   CMP EAX,999999
   JNA Done
   INC ECX
   CMP EAX,9999999
   JNA Done
   INC ECX
   CMP EAX,99999999
   JNA Done
   INC ECX
   CMP EAX,999999999
   JNA Done
   INC ECX
Done: ; Number of decimal digits is in ECX.
vitsoft
  • 5,515
  • 1
  • 18
  • 31
  • 1
    Or use `bsr`, and a lookup table with count and compare threshold for one more decimal digit or not. [Counting number of digits in a number in O(1)](https://stackoverflow.com/a/10723669) – Peter Cordes Apr 21 '21 at 20:16
  • Or another approach is to *multiply* something by 10 in a loop, with 2-cycle latency using `lea edx, [edx+edx*4]` / `add edx,edx`. (Starting with 10 so you get 1 digit for any number < 10). i.e. to roll up your code into a loop. – Peter Cordes Apr 22 '21 at 00:40