2008-11-20 47 views
16

可以Unicode字符被编码和解码为Base64Base64ing Unicode字符

我试图编码字符串'الله',但是当我解码它时,我得到的是'????'。

+0

这将取决于Base64编码程序如何抓取数据,有什么平台和代码?答案是肯定的,他们当然可以。 – 2008-11-20 12:32:24

+0

数据在Delphi中编码并在PHP中解码/使用 – UnkwnTech 2008-11-20 12:35:08

+0

对不起,没有关于Delphi的线索。但我提供了一个答案,证明这个问题与base64 – 2008-11-20 12:40:21

回答

17

Base64将二进制转换为文本。如果要将文本转换为base64格式,则需要先使用某种适当的编码(例如UTF-8,UTF-16)将文本转换为二进制文件。

17

当然可以。这取决于您的语言或Base64例程如何处理Unicode输入。例如,Python的b64例程需要一个编码字符串(因为Base64将二进制文本编码,而不是将Unicode码位编码为文本)。

Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) 
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> a = 'ûñö' 
>>> import base64 
>>> base64.b64encode(a) 
'w7vDscO2' 
>>> base64.b64decode('w7vDscO2') 
'\xc3\xbb\xc3\xb1\xc3\xb6' 
>>> print '\xc3\xbb\xc3\xb1\xc3\xb6' 
ûñö 
>>>  
>>> u'üñô' 
u'\xfc\xf1\xf4' 
>>> base64.b64encode(u'\xfc\xf1\xf4') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.5/base64.py", line 53, in b64encode 
    encoded = binascii.b2a_base64(s)[:-1] 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 
0-2: ordinal not in range(128) 
>>> base64.b64encode(u'\xfc\xf1\xf4'.encode('utf-8')) 
'w7zDscO0' 
>>> base64.b64decode('w7zDscO0') 
'\xc3\xbc\xc3\xb1\xc3\xb4' 
>>> print base64.b64decode('w7zDscO0') 
üñô 
>>> a = 'الله' 
>>> a 
'\xd8\xa7\xd9\x84\xd9\x84\xd9\x87' 
>>> base64.b64encode(a) 
'2KfZhNmE2Yc=' 
>>> b = base64.b64encode(a) 
>>> print base64.b64decode(b) 
الله 
1

您没有指定使用哪种语言,但尝试将字符串转换为字节数组(然而,这是用您选择的语言完成的),然后base64编码该字节数组。

1

在.NET中你可以试试这个(编码):

byte[] encbuf; 

encbuf = System.Text.Encoding.Unicode.GetBytes(input); 
string encoded = Convert.ToBase64String(encbuf); 

...和解码:

byte[] decbuff; 

decbuff = Convert.FromBase64String(this.ToString()); 
string decoded = System.Text.Encoding.Unicode.GetString(decbuff);