How to repeat a byte number inside another number without iterating? if possible...

615 Views Asked by At

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.

3

There are 3 best solutions below

9
On BEST ANSWER

You have a geometric series. You can use the fact that $1+2^8+2^{16}+2^{24}=\frac {2^{32}-1}{2^8-1}$ If you change the number of terms, the only thing that changes is the $32$ exponent.

11
On

It is not entirely clear what you are looking for.

If the number of repetitions is fixed, then you can precompute one number and use this to find the 'repetition number' by just using multiplication.

Suppose you need $r$ repetitions, form the number $n = \sum_{k=0}^{r-1} 2^{8k}$. Then, to repeat the byte $b$, form the number $nb$.

Addendum:

In Python 3.2+ it would be something like int.from_bytes(bytearray(chr(b)*r,'utf-8'),byteorder='little'), where b is the byte and r the repetitions.

1
On

In Python, we can take advantage of string formatting. I'll use string interpolation here:

>>> b = 0x2a
>>> reps = 3
>>> '0x' + ('%02x' % b) * reps
'0x2a2a2a'