Unique Marketing, Guaranteed Results.

Using Ruby Unpack To Save Strings To Integers

April 3rd, 2009 by Aaron Murphy

What does unpack do? It’s used to take a previously packed string of usually binary data and unpack into it’s original binary data. Pack is a method of Array which returns a string. But I wanted to use it to store data in a set of integers.

So I figured I could use unpack to do the job. Here’s how:

"Hello World!".unpack('I*C*')

This gave me an array of integers: [1819043144, 1461726319, 1684828783, 33]

That last one is the carry over from the size of integer to character. I used the “I*” format for unsigned integer and “C*” for unsigned character. The asterisks tells unpack to repeat as many times as it can for that data type.

So you could also do:

"Hello, World!".unpack('C*')

to get [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33], which is also an easy way to get an array of bytes for a string.

References: Ruby Doc Class: String
Ruby Doc Class: Array

  • Facebook
  • Google Bookmarks
  • email
  • NewsVine
  • Slashdot
  • Technorati
  • Yahoo! Buzz
  • BlinkList
  • Print
  • Propeller
Filed under: Programming — Tags: , — Aaron Murphy @ 12:12 pm on April 3, 2009

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment


Copyright © 2005-2010 PMA Media Group. All Rights Reserved . Online Degrees | Train for a Better Career | My Colleges and Careers Site Map