문제

I am currently porting a perl project to ruby and all has been going fine until I reached this pack statement.

$move .= pack('W', int($length));

I understand what it's trying to do, but I can't find any documentation on the 'W' option for perls pack method. So it is a bit hard to find a suitable replacement for ruby.

What this statement does is takes the integer, and converts it to a big endian hex format (I believe).

For example the integer 290 is converted to 0x122, and is then stored as "2201" in the variable $move

Although I cannot confirm that because I can't find documentation on 'W' although it would make sense based on what the rest of the project is doing.

Does anyone know a ruby replacement method that would do the same?

edit: As per a comment below I have found it with some help.

W An unsigned char value (can be greater than 255).

도움이 되었습니까?

해결책

Since the format's introduction in 5.10, pack says:

W  An unsigned char value (can be greater than 255).

For example, the following are equivalent:

  • pack('W', 0x2660)
  • chr(0x2660)
  • "\x{2660}"

For all values of $i, length(pack('W', $i)) is one.


What's the size of a character (string element) in Ruby? Are they 8 bits like C, or larger like Java (16) and Perl (32 or 64)?

If they are limited to 8 bits, there is no direct equivalent of that code in Ruby. You'll need to use an array instead of a string.

If Ruby's character are wide enough to contain the numbers in question (e.g. 290), then a look through the Ruby docs reveals the following:

i.chr
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top