views:

126

answers:

2

what's the maximum number of characters generated by the following statement? i need to format the output properly.

echo base_convert(sprintf('%u',crc32($_string)),10,36);
+2  A: 
crc32($_string)

returns the CRC as 32-bit integer whose max value will be 0xFFFFFFFF which in decimal is 4294967295.

sprintf('%u',crc32($_string))

Will return the above value interpreted as unsigned int.

base_convert(sprintf('%u',crc32($_string)),10,36)

This will convert the previously returned int from base 10 to base 36. Now 4294967295 in base 10 = 1z141z3 in base 36, which is 7 char long. So looks like the MAX length will be 7 char.

codaddict
+1  A: 

I see that you already have an answer, but I'd like to generalize the solution.

The question is how many base 36 digits are required to represent a number having 32 base 2 digits (i.e. bits). The conversion to/from base 10 in the middle is irrelevant to the problem.

The number of digits is determined by the logarithm of the number in the desired base. We know that the base 2 logarithm is 32, so what's the base 36 logarithm?

32 * log(2) / log(36)

My calculator gives me 6.1896449 or so. Since we can't deal with partial digits, you need to round up to 7. This also explains why 6 digits works most of the time.

Mark Ransom
This is correct, but if you're using this fact to write a general number displayer, don't forget that this will tell you to display 0 with no characters. Technically correct, but you may want to check for that special case.Oh, and negative numbers are handled by adding space for the sign, and then working with the absolute values.
swestrup
@swestrup, all very true. And if you're working with signed numbers, you can subtract a bit for the sign and start with 31 bits instead. I didn't include those details because they didn't apply to the original question and would have complicated the answer.
Mark Ransom