Search code examples
phppythonarraystranslate

Python to PHP for-loop array


I'm busy translating a piece of python to PHP. PHP i know, but Python not so much.

Of all the code, I have 5 lines left which I can not translate. Is there someone who is willing to help me with this?

items = []
items.append(s0 >> 0)
items.append(s0 >> 8)
items.append((s0 >> 16) | (s1 << 5))
items.append(s1 >> 3)

newb = b''
for i in items:
        tmp = i.to_bytes((i.bit_length() + 7) // 8, byteorder='little')
        localnewbyte = bytes([tmp[0]])
        newb += localnewbyte

The above part should be something like this, if I'm correct:

    $aItems = [];
    $aItems[] = ($s0 >> 0);
    $aItems[] = ($s0 >> 8);
    $aItems[] = (($s0 >> 16) | ($s1 << 5));
    $aItems[] = ($s1 >> 3);

    for($i = 0; $i < count($aItems); $i++)
    {
    }

But this is as far as I get, please help. Thanks!


Solution

  • Step 0: Understand the input. Without knowing what values s0 and s1 represent:

    s0 is a sequence of at least 3 bytes. I'm going to assume 4:

    <byte-4><byte-3><byte-2><byte-1>
    

    s1 is at least 1 byte. I'm going to assume 1, with the following bits (some of which are ones):

    abcdefgh
    

    The first 5 lines of code lead to the following array:

    aItem = [
        <byte-4><byte-3><byte-2><byte-1>, 
        <byte-4><byte-3><byte-2>, 
        <byte-4><byte-3> or 000abcdefgh00000, 
        000abcde ]
    

    Now we can start answering the question. Line by line:

        newb = b''      # initialize an empty byte literal
        for i in items: # loop over the aItem array
            tmp = i.to_bytes((i.bit_length() + 7) // 8, byteorder='little')
                # little-endian byte order array, with any leading 0 bytes removed.
            localnewbyte = bytes([tmp[0]])
                # the first byte of tmp, which is the rightmost byte in aItem.
            newb += localnewbyte
                # add that byte to newb.
    

    The result is anti-climactic, a 4 byte literal. Depending on whether s0 has 3+ significant bytes or not:

    <byte-1><byte-2><byte-3>000abcde
    

    or

    <byte-1><byte-2>fgh00000000abcde
    

    I'm sure there are many easier ways to achieve this result than the provided code. Did it come from an obfuscated code competition?