Skip to main content
 首页 » 编程设计

php之Python中的空格填充二进制字符串

2025年05月04日11mfrbuaa

我需要将这个 PHP 函数转换成 Python,但我什至不知道什么是空格填充的二进制字符串。

pack('A*', $string); 

Python 有 struct.pack 可能应该使用的东西,但我到此为止。有人可以帮我解释一下这种行为吗?

谢谢!


更新:

这是我需要用 Python 实现的全部代码。直到现在我从未听说过 pack() 所以我试图了解它到底做了什么所以我可以在 Python 中做到这一点:

function getSIGN($PID, $ID, $DESC, $PRICE, $URL, $EMAIL, $PWD) { 
    $bHash = pack('A*', $PID . $ID . $DESC . $PRICE . $URL . $EMAIL); 
    $bPWD = pack('A*', $PWD); 
    $SIGN = strtoupper(hash_hmac('sha256', $bHash, $bPWD, false)); 
    return $SIGN; 
} 

请您参考如下方法:

我认为那是空话。

$string = 'asdf'; 
print pack('A10', $string) . "|<-\n"; 

给你

asdf      |<- 

由于 * 表示“尽可能多地取用”,因此没有任何理由需要填充。

恕我直言,你可以扔掉整行。


回复。你的更新:

pack 函数仍然没有任何作用,除了可能将所有非字符串参数隐式转换为字符串。

以下是您在 Python 中的操作方法。我冒昧地改变了参数的顺序,所以我可以使用参数打包(这根本不像字符串打包;)。

import hmac, hashlib 
 
def get_sign(key, *data): 
     msg = ''.join(str(item) for item in data) 
     h = hmac.new(key, msg, hashlib.sha256) 
     return h.hexdigest().upper() 

PHP:

$ print getSIGN(1234, 456, "foo", '123.45', 'http://example.com', 'foo@example.com', 'blah');   
7FA608240FA2DC04F15DB2CDB58C83F4ED6C28C5C5B4063C5A7605F9D69F170B 

python :

In [12]: get_sign('blah', 1234, 456, "foo", '123.45', 
                  'http://example.com',  'foo@example.com') 
Out[12]: '7FA608240FA2DC04F15DB2CDB58C83F4ED6C28C5C5B4063C5A7605F9D69F170B'