views:

38

answers:

1

Hey there!

I'm trying to convert a big-endian 2 byte string into a numeric port number. I've already got some code, but I have no idea if it's right:

from struct import unpack
def unpack_port(big_endian-port):
   return unpack("!H", big_endian-port)[0]

The port (using Python repr() ) is \x1a\xe1, and I get 6881 out of that function.

Is that correct?

+1  A: 

Yes, '!' is the character that says 'network byte order', and 'H' says '16-bit unsigned integer', so your code is correct. 6881 is typically a Bittorrent port.

In this case, I believe '!' is the correct character. Since it's a port number, I expect your data is coming from a network. But, if you knew your data to be big-endian for some other reason, '>' might be more appropriate. They mean the exact same thing and always will. It's more a matter of commenting your code to indicate intent than any semantic difference.

Omnifarious
Thanks. Just wasn't sure I'd got the formatting flag right.
Ink-Jet