Seite 1 von 1

0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 20:29
von jens
Wie kann ich denn das erreichen: 0x12345678 -> [0x12, 0x34, 0x56, 0x78] ?

Ich hab schon ein wenig mit divmod probiert, komme aber nicht zum richtigen Ergebnis ;(

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 20:41
von BlackJack

Code: Alles auswählen

In [481]: [hex(ord(c)) for c in struct.pack('>i', 0x12345678)]
Out[481]: ['0x12', '0x34', '0x56', '0x78']

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 20:54
von jerch
@jens:
Wenn Du rechnerisch zum Ergebnis kommen willst, ist divmod (bzw. & und >>) schon der richtige Ansatz. Was hast du denn probiert?

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:06
von jens
Hab das hier:

Code: Alles auswählen

        dividend = 0x12345678
        print hex(dividend)
        high_word, low_word = divmod(dividend, 0x10000)
        low_byte1, high_byte1 = divmod(high_word, 0x100)
        low_byte2, high_byte2 = divmod(low_word, 0x100)
        print hex(low_byte1), hex(high_byte1), hex(low_byte2), hex(high_byte2)
Ausgabe:

Code: Alles auswählen

0x12345678
0x12 0x34 0x56 0x78
Also eigentlich richtig. Aber recht umständlich, oder nicht?

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:14
von jerch
Naja was heisst umständlich, recht explizit ausgeschrieben würd ich sagen, da es auch kürzer geht:

Code: Alles auswählen

def bytesplit(n):
    while n:
        yield n & 255
        n >>= 8

list(hex(i)for i in bytesplit(0x12345678))[::-1]

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:16
von Sirius3
So:

Code: Alles auswählen

>>> [0x12345678>>(a<<3)&0xff for a in (3,2,1,0)]
[18, 52, 86, 120]

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:23
von fail
@Sirius3

Code: Alles auswählen

[hex(0x12345678>>(a<<3)&0xff) for a in (3,2,1,0)]

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:24
von jens
Ach, die Breite ist auch wichtig...

Also nicht 0x1234 -> [0x12, 0x34]
sondern: 0x1234 -> [0x00, 0x00, 0x12, 0x34]

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:26
von jens
fail hat geschrieben:@Sirius3

Code: Alles auswählen

[hex(0x12345678>>(a<<3)&0xff) for a in (3,2,1,0)]
Das nehme ich! Danke!

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 21:28
von BlackJack

Code: Alles auswählen

In [484]: [hex(0x12345678 >> (i * 8) & 0xff) for i in reversed(xrange(4))]
Out[484]: ['0x12', '0x34', '0x56', '0x78']

Re: 0x12345678 -> [0x12, 0x34, 0x56, 0x78]

Verfasst: Montag 30. Juni 2014, 22:03
von jens
Dafür habe ich das gebraucht: https://github.com/jedie/DragonPy/commi ... 2f9972d62f

Danke euch allen!