Bytes and integers and concatenation and python

被刻印的时光 ゝ 提交于 2019-12-23 12:44:52

问题


I have 2 32bit unsigned integers..

777007543 and 114997259

and the string of bytes..

0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58

How do I get python to give me the concatenation of these 3 such that I have...

0x2E 0x50 0x31 0xB7 0x06 0xDA 0xB8 0x0B 0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58

I would then run that through an md5 hash and get...

0x30 0x73 0x74 0x33 0x52 0x6C 0x26 0x71 0x2D 0x32 0x5A 0x55 0x5E 0x77 0x65 0x75

If anyone could run that through in python code it would be much appreciated


回答1:


import struct
import hashlib

x = struct.pack('>II8B', 777007543, 114997259, 0x47, 0x30, 0x22, 0x2D, 0x5A, 0x3F, 0x47, 0x58)
hash = hashlib.md5(x).digest()

print [hex(ord(d)) for d in x]
(output) ['0x2e', '0x50', '0x31', '0xb7', '0x6', '0xda', '0xb8', '0xb', '0x47', '0x30', '0x22', '0x2d', '0x5a', '0x3f', '0x47', '0x58']

print [hex(ord(d)) for d in hash]
(output) ['0x30', '0x73', '0x74', '0x33', '0x52', '0x6c', '0x26', '0x71', '0x2d', '0x32', '0x5a', '0x55', '0x5e', '0x77', '0x65', '0x75']



回答2:


q = hex(777007543) + hex(114997259)[2:] + '4730222d5a3f4758'

just do this. here's why it works:

>>> num1, num2
(777007543, 114997259)
>>> hex(num1), hex(num2)
('0x2e5031b7', '0x6dab80b')
>>> hex(num1) + hex(num2) + '0x4730222d5a3f4758'
'0x2e5031b70x6dab80b0x4730222d5a3f4758'
>>> hex(num1) + hex(num2)[2:] + '4730222d5a3f4758'
'0x2e5031b76dab80b4730222d5a3f4758'
>>> int(_, 16)
3847554995347152223960862296285071192L

it's not difficult however to deal exactly with the representation you showed in your answer, if you want

edit:

here is what scott griffhits said. He's right ;)

"

Using hex only works here because the numbers are large enough to need 8 hex digits. We need to use a format, for example '{0:08x}{1:08x}'.format(num1, num2) will pad the hex with up to eight zeros.

"




回答3:


This will give you a list of all the values you want,

>>> [777007543 >> i & 0xff for i in xrange(24,0,-8)] + \
... [114997259 >> i & 0xff for i in xrange(24,0,-8)] + \
... map(ord, stringofbytes)

or even better (from the other thread you started),

>>> struct.unpack('>12B', \
... struct.pack('>L', 777007543) + struct.pack('>L', 114997259) + '.P1\xb7')

If you then want to make this a string to pass to your md5 hash,

>>> map(chr, _)

I am assuming that each byte of the string is supposed to represent a 1byte number.



来源:https://stackoverflow.com/questions/4595161/bytes-and-integers-and-concatenation-and-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!