【问题标题】:How to decode utf8 characters with ruby Base64如何使用 ruby​​ Base64 解码 utf8 字符
【发布时间】:2021-06-09 23:32:22
【问题描述】:

正如标题所描述的,我该怎么做?

require 'base64'

text = 'éééé'
encode = Base64.encode64(text)
Base64.decode64(encode)

Result: éééé instead of \xC3\xA9\xC3\xA9

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

当你decode64 时,你会得到一个带有BINARY(又名ASCII-8BIT)编码的字符串:

Base64.decode64(encode).encoding
# => #<Encoding:ASCII-8BIT>

诀窍是强制应用特定的编码:

Base64.decode64(encode).force_encoding('UTF-8')
# => "éééé"

这假定您的字符串是有效的 UTF-8,但可能不是,因此请谨慎使用。

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2011-10-31
    相关资源
    最近更新 更多