Ruby: create a String from bytes

前端 未结 5 1293
眼角桃花
眼角桃花 2020-12-23 19:44

I would like to build a string from a byte value.

I currently use:

str = \" \"
str[0] = byte

This seems to work fine but I find it

相关标签:
5条回答
  • 2020-12-23 20:15

    for 1.9 you need:

    [195,164].pack('c*').force_encoding('UTF-8')
    
    0 讨论(0)
  • 2020-12-23 20:23

    There is a much simpler approach than any of the above: Array#pack:

    >> [65,66,67,68,69].pack('c*')
    =>  "ABCDE"
    

    I believe pack is implemented in c in matz ruby, so it also will be considerably faster with very large arrays.

    Also, pack can correctly handle UTF-8 using the 'U*' template.

    0 讨论(0)
  • 2020-12-23 20:23

    If bytes is an array of Fixnum's you could try this:

    bytes.map {|num| num.chr}.join
    

    or this:

    s = ''
    bytes.each {|i| s << i}
    
    0 讨论(0)
  • 2020-12-23 20:25

    can't remember if there is a single function that does that:

    >> a = [65,66,67]
    => [65, 66, 67]
    >> a.map {|x| x.chr}.join
    => "ABC"
    
    0 讨论(0)
  • 2020-12-23 20:27

    This isn't the OP's question, but if you have just a single byte (not in an array) and want to make a string out of it, use chr

    c = 65
    => 65
    c.chr
    => "A"
    c.chr.class
    => String
    
    0 讨论(0)
提交回复
热议问题