开发者

Ruby equivalent to .NET's Encoding.ASCII.GetString(byte[])

开发者 https://www.devze.com 2023-01-02 08:31 出处:网络
Does Ruby have an equivalent to .NET\'s Encoding.ASCII.GetString(byte[])? Encoding.ASCII.GetString(bytes[]) 开发者_如何学Ctakes an array of bytes and returns a string after decoding the bytes using t

Does Ruby have an equivalent to .NET's Encoding.ASCII.GetString(byte[])?

Encoding.ASCII.GetString(bytes[]) 开发者_如何学Ctakes an array of bytes and returns a string after decoding the bytes using the ASCII encoding.


Assuming your data is in an array like so (each element is a byte, and further, from the description you posted, no larger than 127 in value, that is, a 7-bit ASCII character):

array =[104, 101, 108, 108, 111]

string = array.pack("c*") 

After this, string will contain "hello", which is what I believe you're requesting.

The pack method "Packs the contents of arr into a binary sequence according to the directives in the given template string".

"c*" asks the method to interpret each element of the array as a "char". Use "C*" if you want to interpret them as unsigned chars.

http://ruby-doc.org/core/classes/Array.html#M002222

The example given in the documentation page uses the function to convert a string with Unicode characters. In Ruby I believe this is best done using Iconv:

require "iconv"
require "pp"

#Ruby representation of unicode characters is different
unicodeString = "This unicode string contains two characters " +
                "with codes outside the ASCII code range, " +
                "Pi (\342\x03\xa0) and Sigma (\342\x03\xa3).";

#printing original string
puts unicodeString 

i = Iconv.new("ASCII//IGNORE","UTF-8")

#Printing converted string, unicode characters stripped
puts i.iconv(unicodeString)
bytes = i.iconv(unicodeString).unpack("c*")
#printing array of bytes of converted string
pp bytes

Read up on Ruby's Iconv here.

You might also want to check this question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号