[英]Encode to base64 with Php gives different result than with Python 3
I am trying to convert a code in Php to Python, it consists of encoding a variable obtained with the chr function with base64 using the base64_encode function. 我试图将Php中的代码转换为Python,它包括使用base64_encode函数对使用base64的chr函数获得的变量进行编码。
Here is the code in Php: 这是Php中的代码:
$data = chr(ord('a')+ord('b'));
$data = base64_encode($data);
echo $data;
result: 结果:
ww==
Here is what I tried to do in Python: 这是我在Python中尝试做的事情:
from base64 import b64encode
data = chr(ord('a')+ord('b'))
data = b64encode(data.encode()) // data.encode() is mandatory or I get an error saying that b64encode require a bytes-like object
print(data)
result: 结果:
b'w4M='
Thank you for your help 谢谢您的帮助
Aymeric 艾默里克
I don't know if it's the real answer to the question, but the problem is that python string from version 3 are in unicode. 我不知道这是否是问题的真正答案,但问题是版本3的python字符串是unicode。 so the php-code can be replaced:
所以php代码可以替换:
<?php
$data = chr(ord('a')+ord('b'));
$data = utf8_encode($data);
echo base64_encode($data); //w4M=
or you can use https://www.php.net/manual/en/function.mb-chr.php for this 或者您可以使用https://www.php.net/manual/en/function.mb-chr.php
so for changing python code to work it as php - you need to encode data in latin-1: 因此,要更改python代码以将其作为php工作 - 您需要在latin-1中编码数据:
from base64 import b64encode
data = chr(ord('a')+ord('b')).encode('latin-1')
data = b64encode(data)
print(data) # b'ww=='
print(data.decode()) # ww==
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.