Skip to content

Instantly share code, notes, and snippets.

@Nurdok
Last active June 18, 2025 08:46
Show Gist options
  • Select an option

  • Save Nurdok/4096182 to your computer and use it in GitHub Desktop.

Select an option

Save Nurdok/4096182 to your computer and use it in GitHub Desktop.
Python Conversion

Python Number Conversion Chart

From To Expression
45 "45" str(data)
45 "101101" bin(data)
45 "2D" hex(data)
45 "\x00\x00\x00\x2d" struct.pack('!i', data)
"45" 45 int(data)
"45" "3435" data.encode('hex')
"101101" 45 int(data, 2)
"2D" 45 int(data, 16)
"2D" "\x2d" binascii.unhexlify(data) or data.decode('hex')
"\x00\x00\x00\x2d" 45 struct.unpack('!i', data)[0]
"\x2d" "2D" binascii.hexlify(data)
"3435" "45" data.decode('hex')

Comments are welcome here or in my original blog post regarding this table.

@havenwood
Copy link
Copy Markdown

@chris-martin Good point, I wouldn't. Except for just this. :P

@havenwood
Copy link
Copy Markdown

Finished the Ruby translation, but gosh the "45" to "3435" and vice-versa are fugly.

@kindall
Copy link
Copy Markdown

kindall commented Apr 20, 2013

@chris-martin In Python 2.x, str is basically a byte array. In Python 3.x, str is a Unicode string. We're looking at Python 2.x here, it seems.

@zwegner
Copy link
Copy Markdown

zwegner commented Apr 20, 2013

@Niggler If you don't know what base it's in, you can specify a base of 0:
int('055', 0) -> 45 or int('0x55', 0) -> 85

@marcinantkiewicz
Copy link
Copy Markdown

I'm not sure what to do with "\x00\x00\x00\x2d". What is this encoding (and why would you want it)?

It's a 4-byte int in the network byte order.

@plq
Copy link
Copy Markdown

plq commented Apr 21, 2013

@chris-martin, @havenwood to give you a real-world example for the hex encoding ("45" => "3435"): http://books.xmlschemata.org/relaxng/ch19-77143.html

this is quite inefficient, I know, but you sometimes need it for backwards compatibility.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment