How to Convert String to Bytes in Ruby

How to convert string to bytes in Ruby?

Ruby already has a String#each_byte method which is aliased to String#bytes.

Prior to Ruby 1.9 strings were equivalent to byte arrays, i.e. a character was assumed to be a single byte. That's fine for ASCII text and various text encodings like Win-1252 and ISO-8859-1 but fails badly with Unicode, which we see more and more often on the web. Ruby 1.9+ is Unicode aware, and strings are no longer considered to be made up of bytes, but instead consist of characters, which can be multiple bytes long.

So, if you are trying to manipulate text as single bytes, you'll need to ensure your input is ASCII, or at least a single-byte-based character set. If you might have multi-byte characters you should use String#each_char or String.split(//) or String.unpack with the U flag.


What does // mean in String.split(//)

// is the same as using ''. Either tells split to return characters. You can also usually use chars.

Ruby: create a String from bytes

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.

Ruby Newbie Needs to Convert a String to Byte Array with Some Padding

Something like this? You should probably check for edge cases like multibyte chars.

"my string"[0..15].ljust(16,'0')

Convert a string of 0-F into a byte array in Ruby

To get Integer — just str.hex. You may get byte array in several ways:

str.scan(/../).map(&:hex)
[str].pack('H*').unpack('C*')
[str].pack('H*').bytes.to_a

See other options for pack/unpack here: http://ruby-doc.org/core/classes/String.html#method-i-unpack

And examples here: http://www.codeweblog.com/ruby-string-pack-unpack-detailed-usage/

Convert string to two byte hex unicode in Ruby on Rails

I like fun ones like these. :) Try this:

input.codepoints.map { |c| "%04X" % c }.join

What I see:

[1] pry(main)> x = "\u03A9\u03A8\u0398"
=> "ΩΨΘ"
[2] pry(main)> x.codepoints.map { |c| "%04X" % c }.join
=> "03A903A80398"

convert string number with bytes to integer in rails ( 32MB - 32.megabytes)

There's filesize

It's quite trivial to write your own:
But you can write your own:

def convert_size_to_bytes
md = match(/^(?<num>\d+)\s?(?<unit>\w+)?$/)
md[:num].to_i *
case md[:unit]
when 'KB'
1024
when 'MB'
1024**2
when 'GB'
1024**3
when 'TB'
1024**4
when 'PB'
1024**5
when 'EB'
1024**6
when 'ZB'
1024**7
when 'YB'
1024**8
else
1
end
end


Related Topics



Leave a reply



Submit