Is there anyway we can get the length of an integer

The programming problem is supposed to take a decimal number from a user and turn it into a binary number

here is my code

1
2
3
4
5
6
for (int i=0; i< count; i++)
	{
		binary[i] = decimal % 2;
		decimal = decimal/2;
		}
	cout << binary[2] << endl;


decimal is the number entered by the user.
binary [] is the char array and count is... you know how many times the for loop will turn. So my question is, how do i know the length of the number ? does anyone know any function that shows the integer length ? because its impossible to know what count is equal to. like 100 is 3.
Thanks in advance
Last edited on
closed account (o3hC5Di1)
Hi there,

I believe the easiest way would be to convert decimal to a string, then get the length of the string.

If you can only use c-strings, you can use: http://www.cplusplus.com/reference/cstdlib/itoa/?kw=itoa
and strlen().
Otherwise, you could use

1
2
std::string tmp = std::to_string(decimal);
int count = tmp.size();


Note that std::to_string may throw an exception if the input is invalid.

All the best,
NwN
The number of binary digits is

int(log_base2(decimal)) + 1

which can be calculated by int(log(decimal)/log(2)) + 1

There is some danger of under-representing exact powers of 2. e.g. log_base2(4) = 2 but possibly some calculation error would lead to 1.9999999999999999 which would then be rounded down to 1

The simplest option to be safe is to add an extra char just in case. i.e. use

int(log(decimal)/log(2)) + 2 as the space to reserve
http://www.cplusplus.com/reference/cmath/log2/

1
2
3
4
while(decimal not_eq 0){
   //...
   decimal/=2;
}
Topic archived. No new replies allowed.