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 ugly and not very scalable to strings longer than 1 character.
Any idea?
Join Stack Overflow to learn, share knowledge, and build your career.
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.
c*
. You really want C*
. See: ruby-doc.org/core-1.9.3/Array.html c
is for "8-bit signed (signed char)", C
is for "8-bit unsigned (unsigned char)"
– David J.
Aug 6 '12 at 3:48
for 1.9 you need:
[195,164].pack('c*').force_encoding('UTF-8')
C*
because you want unsigned integers. c*
is for signed integers. Note that: "ä".unpack('c*')
== [-61, -92]
. What you want is: "ä".unpack('C*')
== [195, 164]
– David J.
Aug 6 '12 at 3:51
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"
[195,164].pack('c*').force_encoding('UTF-8')
– David J.
Aug 6 '12 at 3:30
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}
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