SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Aug 2005
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP's bin2hex in Ruby?

    Hi, I'm having a bit of a trouble converting a legacy app to Ruby.

    Can anyone tell me how to get the equivalent of PHP's bin2hex function in Ruby?
    I've found a few solutions but they don't seem to return the same result PHP's does, which is a must for me at this point.

    Any help appreciated

  2. #2
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First: do you really need this? If you are working binary numbers there might be better ways to do what you want to do.

    to_i and to_s accept radices (?):

    Code:
    255.to_s(16) => "FF"
    "10101".to_i(2) => 21
    "10101".to_i(2).to_s(16) => "15"

  3. #3
    SitePoint Wizard dreamscape's Avatar
    Join Date
    Aug 2005
    Posts
    1,080
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP's bin2hex doesn't convert a binary number string to hexadecimal. It converts binary data to a hexadecimal representation. One example for use might be a hashing or signature algorithm that outputs binary data, but you need to store in a readable format. In PHP you can use bin2hex to do this.

    bin2hex is also equivalent to unpack("H*", $data), aside from one returns a string and the other returns an array containing a single element that has the string. But the strings are the same.

    A simple test shows this (I'm using ASCII data, but binary data should also get the same result for each):
    Code:
    php> var_dump(bin2hex('my data'));
    string(14) "6d792064617461"
    
    php> var_dump(unpack('H*', 'my data'));
    array(1) {
      [1]=>
      string(14) "6d792064617461"
    }
    
    php>
    There's an unpack method for Strings in ruby, which you should theoretically get the same results if you use that. The same simple test in Ruby shows that you do:
    Code:
    PowerBook-G4:~ dreamscape$ irb --simple-prompt
    >> "my data".unpack("H*")
    => ["6d792064617461"]
    That should be what you're looking for, though I haven't tested with true binary data.

    Note that it is a capital H you want to use, which starts with the most significant nibble, the same as bin2hex does. A lower case h will start with the least significant nibble, and not give the same results.
    <.smarter.web.development.>
    PHP Stuff: Plexus | Chocolate (BDD Framework... coming soon)
    Graphite


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •