Reputation: 2998
From the docs, unpack
does:
Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted.
And the "C"
format means 8-bit unsigned (unsigned char)
.
But what does this actually end up doing to the string I input? What does the result mean, and if I had to do it by hand, how would I go about doing that?
Upvotes: 2
Views: 2600
Reputation: 535315
But what does this actually end up doing to the string I input
It doesn't do anything to the input. And the input is not really a string here. It's typed as a string, but it is really a buffer of binary data, such as you might receive by networking, and your goal is to extract that data into an array of integers. Example:
s = "\01\00\02\03"
arr = s.unpack("C*")
p(arr) # [1,0,2,3]
That "string" would be meaningless as a string of text, but it is quite viable as a data buffer. Unpacking it allows you examine the data.
Upvotes: 5
Reputation: 121000
It converts each subsequent char to it’s integer ordinal as String#ord
does. That said,
string.unpack 'C*'
is an exact equivalent of
string.each_char.map(&:ord)
Upvotes: 7