# Thread: Counting number of digits in a variable

1. ## Counting number of digits in a variable

Dear friends,

I have an assignment to convert from binary to decimal... I know how to do it but only thing is I need to know how many digits are stored in my variable, for example :

110101

so if somehow I know there is 6 numbers I can make my loop and convert it to decimal very easy.

Thanks.

2. strlen()

3. That's only if the variable is stored in a string. If it's stored in an int, you can use a combination of modulus (%) and division (/) in a loop to do the conversion and to figure out how many digits there are. Come to think of it, you can probably do it with just division.

For example, to count the number of binary digits:
Code:
```int number = 42;
int digits = 0;
while(number) {
digits ++;
number /= 2;
}```

4. That should be

Code:
`number /= 10`
not

Code:
`number /= 2`

5. Originally Posted by KBriggs
That should be

Code:
`number /= 10`
not

Code:
`number /= 2`
That should be
Code:
`number /= 2;`
not
Code:
`number /= 10;`

6. Unless one really wants to deal with negative integers, it may be better to use say, unsigned int, and initialise digits to:
Code:
`unsigned int digits = number == 0;`
in order to account for the case where the number is 0.

7. Haha oops I was thinking in decimal