Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I am attempting to decrypt a number encrypted by another program that uses the BouncyCastle library for Java.

In Java, I can set the key like this: key = Hex.decode("5F3B603AFCE22359");

I am trying to figure out how to represent that same step in Ruby.

like image 206
Brandon Yarbrough Avatar asked Sep 22 '10 18:09

Brandon Yarbrough


People also ask

How do I convert a string to an array in Ruby?

Strings can be converted to arrays using a combination of the split method and some regular expressions. The split method serves to break up the string into distinct parts that can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.

How do I convert a string to a number in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

Can we convert string to byte array in C#?

The Encoding. GetBytes() method converts a string into a bytes array. The example below converts a string into a byte array in Ascii format and prints the converted bytes to the console.


1 Answers

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/

like image 188
Nakilon Avatar answered Sep 18 '22 05:09

Nakilon