unpack("N*")

Hi,

I'm trying to unpack a string into network byte order (big-endian), such
as the following method:

# Convert an 8-bit or 16-bit string to an array of big-endian words
# In 8-bit function, characters >255 have their hi-byte silently
ignored.
def str2binb(str)
  bin =
  mask = (1 << 8) - 1
  i = 0
  while (i < str.length * 8)
    bin[i>>5] ||= 0
    bin[i>>5] |= (str[i / 8] & mask) << (32 - 8 - i%32)
    i += 8
  end
  bin
end

But after using unpack("N*") method (according to
class String - RDoc Documentation), the result is
not exactly the same. For instance:

str2binb("Abcdefghijklmnopqrstuvwxyz")

=> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,
1970698104, 2038038528]

"Abcdefghijklmnopqrstuvwxyz".unpack("N*")

=> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,
1970698104]

Moreover, if I try "a".unpack("N*"), Ruby returns a void array...

Thanks for any suggestions.

···

--
Posted via http://www.ruby-forum.com/\.

Zangief Ief wrote:

Hi,

I'm trying to unpack a string into network byte order (big-endian), such
as the following method:

# Convert an 8-bit or 16-bit string to an array of big-endian words
# In 8-bit function, characters >255 have their hi-byte silently
ignored.
def str2binb(str)
  bin =
  mask = (1 << 8) - 1
  i = 0
  while (i < str.length * 8)
    bin[i>>5] ||= 0
    bin[i>>5] |= (str[i / 8] & mask) << (32 - 8 - i%32)
    i += 8
  end
  bin
end

But after using unpack("N*") method (according to
class String - RDoc Documentation), the result is
not exactly the same. For instance:

str2binb("Abcdefghijklmnopqrstuvwxyz")

=> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,
1970698104, 2038038528]

"Abcdefghijklmnopqrstuvwxyz".unpack("N*")

=> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,
1970698104]

Moreover, if I try "a".unpack("N*"), Ruby returns a void array...

Better pad with null chars (\0) up to a multiple of 4 bytes if you want the same behavior. I guess unpack("N*") stops if there is not a full 4 chars.

···

--
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Many thanks! :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.