tags:

views:

141

answers:

3

I know that you can split a power-of-two number in half like so:

halfintR = some32bitint & 0xFFFF
halfintL = some32bitint >> 16

can you do the same thing for an integer which is bounded by a non-power of two space?

(say that you want your range to be limited to the set of integers that will fit into 4 digit base 52 space unsigned)

+1  A: 

Well, of course. & 0xffff is the same as % 0x10000 and >> 16 is the same as / 0x10000. It is just that division by a power-of-two is more efficient when done with bit operations like shifting and masking. Division works with any number (within range of representation).

laalto
Well, I'd argue that the bit-shifting thing is easier to grasp for programmers than using modulus or division at that point. In any case, write what you mean and let the compiler do the rest. Premature optimization and stuff :). If you actually want to divide by two then by all means write it as a division by two and not as a bitshift.
Joey
Not to mention that a compiler is likely to find the most efficient way to do modulos and divisions by constant powers of two. In almost all cases, they know more about producing good code than you do.
David Thornley
+1  A: 

You could use the following

rightDigits = number % 2704 // 52 squared
leftDigits = number / 2704
Patrick McDonald
why squared? if it were a 6 digit space, would I use 52**3?
ʞɔıu
exactly, you use 52**2 to get the last 2 digits
Patrick McDonald
what if it were 5 digits, would I use (52 * 52 * 26)? Also, to reverse this operation I would just use (leftDigits * 52**2) + rightDigits, right?
ʞɔıu
yes you reverse it with (left2Digits * 52**2) + rightdigits
Patrick McDonald
I don't think you can split a 5 digit number evenly without representing it in another base
Patrick McDonald
+1  A: 

Once you realize that the & and >> are used for doing modulo und division calculation respectively, you can write what you want as:

lower = some4DigitsNumberBase52 % (52 * 52)
upper = some4DigitaNumberBase52 / (52 * 52)

This is the basis for doing base calculation. You can also derive the solution from the algorithm that displays a number in a specific base: how do you come up with the rightmost two digits and the 2 leftmost digits.

Pierre