Search code examples
pythonrubyequivalent

Equivelant way of performing Ruby's array.pack in Python


I have a Ruby function that looks like this:

def domain_request
  pkt = "0300000c02f0800400010001"
  return [pkt].pack("H*")
end

Basically what I would like to do is perform the same thing in Python (if you could also provide reference to the pack formats it would be greatly appreciated) I've attempted to do so from a bytearray however, I'm at a loss at this point. Any help would be greatly appreciated, thank you.


Solution

  • This looks like what you want

    from binascii import unhexlify
    
    str = "0300000c02f0800400010001"
    unhexlify(str)
    

    Although the output of ruby appears slightly different, comparing these in both ruby and python both are true, this code works in both python and ruby:

    s1 = "\x03\x00\x00\x0c\x02\xf0\x80\x04\x00\x01\x00\x01"
    s2 = "\x03\x00\x00\f\x02\xF0\x80\x04\x00\x01\x00\x01"
    
    s1 == s2 #=> true or True in python