1

I have the following python code, which converts a binary string into plain-text:

import bin ascii
n = int('01100001011000100110001101100100', 2)
binascii.unhexlify('%x' % n)

This code functions properly, but I don't understand what's going on here.

  1. What is the purpose of the "2" at the end of the int declaration?
  2. What is the purpose of the "'%x' % n" argument?
1
  • The first creates an integer out of string and the '2' marks the string as integer representation in base 2. Commented Oct 6, 2017 at 0:43

1 Answer 1

1

What is the purpose of the 2 at the end of the int declaration?

According to the documentation, int can take a second argument: the base of the first argument.

What is the purpose of the '%x' % n argument?

%x in a string indicates that an item will be formatted to hexadecimal with lowercase letters. '%x' % n. It is similar to the builtin hex function, except it doesn't have the leading 0x in the string. An equivalent expression would be format(n, 'x').

Sign up to request clarification or add additional context in comments.

1 Comment

Note: It's only coincidence this works. If the int value hadn't happened to require an even number of hex characters to represent, binascii.unhexlify would have barfed (it won't try zero padding on either end). On Python 3, you could get faster, correct behavior even when the int formats as odd-length hex, without binascii, by replacing the unhexlify line with: n.to_bytes((n.bit_length() + 7) // 8, 'big') (which directly converts from int to bytes without producing an intermediate str at all, avoiding reliance on the hex representation entirely)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.