Ok, I need a bit of help from my Math/Computer geeks out there. In the curse of an optimization for a program I am writing in Python, I found the following problem: for a given byte value, I need to get an arbitrary number of those bytes consecutives within another numeric variable.
This is very easy to do with iterations, let's say:
byte = 0x0f
reps = 3
result = 0
for i in range(0, reps):
result = (result << 8) | byte
(Note that result << 8 is the same than result * 256, though sometimes is faster. I don't know if this is the case with Python, actually, maybe the language processor itself is able to do that conversion before compiling)
I haven't tested that code, but it should work. For the given byte and number of repetitions it should give a result of 0x0f0f0f
Now, the problem is that I am convinced that there has to be way to obtain such result WITHOUT iterating through a loop. I think there should be an arithmetic relation between the byte value and the number of reps, so I could be able to obtain that result with the need of iterating.
But after several hours struggling with this, I have not been able to found such, even when I have this in front of my face with those damn numbers laughing at me:
hex(0x0f * (2**24 + 2**16 + 2**8 + 1))
'0xf0f0f0f'
There have to be a general way to find that
(2**24 + 2**16 + 2**8 + 1)
multiplier based on the number of reps (it his case it is for three repetitions, for two you should remove
2**24 +
and for four you should add
2**32 +
at the start), instead of iterating. There's a clear relation between those exponentials, so IT HAS TO BE A WAY THERE SOMEWHERE CONCEALED TO MY EYES!!!
Any hints are very welcomed... Even one demonstrating the impossibility of doing want I what to do without a loop.
PS. Excuse my lack of Math skills, that's why my example is a program in Python instead a Mathematical expression that I think would have fit better here.
https://upload.wikimedia.org/math/8/c/1/8c13104b74e13a61a0beb44fa8d6e46b.png
Let's say n=1,000,000, so you can either use the approach at the right of the equal symbol, and hence do a loop with 1,000,000 iterations, or use the one at the left of the equal symbol, and have it done with just one arithmetic calculation. Which approach you think it would be faster?
– Fran Marzoa Mar 12 '16 at 20:58