在Ruby中将整数字符串转换为字节数组 [英] Convert a string of integers to byte array in Ruby

查看:1428
本文介绍了在Ruby中将整数字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数字符串72101108108111,但它是一个字符串,表示原始字符串Hello的字节。

I have a string of integer "72101108108111" but it is a string representing bytes of original string "Hello".

如何将72101108108111转换为Ascii Ruby中的字符串Hello?

How can I convert "72101108108111" to Ascii string "Hello" in Ruby?

推荐答案

在评论中澄清你的问题(与标题无关):

Answering your question as clarified in comments (which has nothing to do with the title):


我需要将字符串编码/解码为Base58

I need to encode/decode a string to Base58

编辑:现在作为一个类(使用base58 gem):

now as a class (using base58 gem):

require 'base58'

class Base58ForStrings
  def self.encode(str)
    Base58.encode(str.bytes.inject { |a, b| a * 256 + b })
  end

  def self.decode(b58)
    b = []
    d = Base58.decode(b58)
    while (d > 0)
      d, m = d.divmod(256)
      b.unshift(m)
    end
    b.pack('C*').force_encoding('UTF-8')
  end
end

Base58ForStrings.encode('Hello こんにちは')
# => "5scGDXBpe3Vq7szFXzFcxHYovbD9c" 
Base58ForStrings.decode('5scGDXBpe3Vq7szFXzFcxHYovbD9c')
# => "Hello こんにちは"

适用于任何UTF-8字符串。

Works for any UTF-8 string.

这篇关于在Ruby中将整数字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆