Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • unpack

    Posted on June 28th, 2009 RubyLove No comments

    The unpack function decodes a binary string into an array according to the format given as a parameter.

    PHP

    $binary_string = pack("nvc*", 0x1234, 0x5678, 65, 66);
    $array = unpack("nvc*", $binary_string);

    Ruby

    a = [0x1234, 0x5678, 65, 66];
     
    binary_string = a.pack("nvc*");
     
    my_array = binary_string.unpack('nvc*');
  • pack

    Posted on June 25th, 2009 RubyLove No comments

    The pack function packs the given arguments into a binary string according to format provided as a parameter.

    PHP

    $binary_string = pack("nvc*", 0x1234, 0x5678, 65, 66);

    Ruby

    a = [0x1234, 0x5678, 65, 66];
     
    binary_string = a.pack("nvc*");
  • bin2hex

    Posted on June 22nd, 2009 RubyLove No comments

    The bin2hex function converts any string into an ASCII string containing the hexadecimal represenation of the original string. As the name of the function suggests, bin2hex is particularly useful to make a human-readable representation of binary strings.

    PHP

    $binary_string = pack("nvc*", 0x1234, 0x5678, 65, 66);
     
    echo bin2hex($binary_string);
     
    => // 123478564142

    Ruby doesn’t have a function equivalent to PHP’s bin2hex, but Bytes::unpack with a format string of H* will achieve the same functionality.

    Ruby

    a = [0x1234, 0x5678, 65, 66];
     
    binary_string = a.pack("nvc*");
     
    puts binary_string.unpack('H*');
    => # 123478564142