简体   繁体   English

Python包到PHP包

[英]Python pack to PHP pack

I am trying convert a Python script to PHP. 我正在尝试将Python脚本转换为PHP。 However I am having trouble getting the format right. 但是我无法正确设置格式。

Python: 蟒蛇:

print(hashlib.sha1(struct.pack('L', 1)).hexdigest()) 

Output: 输出:

3da89ee273be13437e7ecf760f3fbd4dc0e8d1fe

PHP: PHP:

echo sha1(pack('L', 1));

Output: 输出:

3c585604e87f855973731fea83e21fab9392d2fc

Can someone please point me in right direction to get the same output in both languages? 有人可以指出正确的方向,以便在两种语言中获得相同的输出吗?

The differences occurs because of different integer sizes. 之所以发生差异,是因为整数大小不同。 While L in the php version of pack() uses hardcoded 32bit integers, Python by default uses the machine integer size. php版本的pack()中的L使用硬编码的32位整数,而Python默认情况下使用机器整数大小。 If you are working on a 64bit system you'll notice the difference. 如果您使用的是64位系统,则会注意到其中的区别。 (As shown in the question) (如问题所示)

You need to use the = in python to standardize the aligment and the size: 您需要在python中使用=来标准化匹配度大小:

print(hashlib.sha1(struct.pack('=L', 1)).hexdigest())

Output: 输出:

3c585604e87f855973731fea83e21fab9392d2fc

Please refer to this docs: 请参考此文档:

This appears to be a 32 vs 64-bit issue. 这似乎是32位和64位问题。 Are you running a 64-bit version of Python? 您是否正在运行64位版本的Python?

Note that according to the Python docs , L is an "unsigned long". 请注意,根据Python文档L是“无符号长”。 Since you're not specifying a byte order, size and alignment character, Python will default to native . 由于您未指定字节顺序,大小和对齐字符,因此Python将默认为native On Linux, that means 8 bytes on 64-bit, and 4 bytes on 32-bit. 在Linux上,这意味着64位为8个字节,而32位为4个字节。

It's always best to tell Python exactly what you mean when working with binary data: 始终最好告诉Python使用二进制数据时的确切含义:

  • < for little-endian, standard size, or <用于小端,标准尺寸,或
  • > for big-endian, standard size. >对于大端,标准大小。

This will eliminate any differences, depending on what type of machine you're running on. 这将消除任何差异,具体取决于您所运行的计算机类型。

This example shows that you're probably using a 64-bit build of python, as L == Q (64-bit). 此示例表明您可能正在使用64位版本的python,如L == Q (64位)。

>>> print(hashlib.sha1(struct.pack('<I', 1)).hexdigest())
3c585604e87f855973731fea83e21fab9392d2fc

>>> print(hashlib.sha1(struct.pack('<Q', 1)).hexdigest())
3da89ee273be13437e7ecf760f3fbd4dc0e8d1fe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM