0

I'm trying to convert some binary output from a file to different types, and I keep seeing odd things.

For instance, I have:

value = '\x11'

If you do

bin(ord(value))

you get the output

'0b10001'

whereas I was hoping to get

'0b00010001'

I'm basically trying to read in a 32 byte header, turn it into 1's and 0's, so I can grab various bits that have different meanings.

3 Answers 3

2

Why not just use bitwise operators?

def is_bit_set(i, x):
    """Check if the i-th bit in x is set"""
    return x & (1 << i) > 0
Sign up to request clarification or add additional context in comments.

Comments

2

To get the desired output, try:

"0b{:08b}".format(ord(value))

If efficiency is your concern, it's recommended to use native binary representation instead of literal(string) binary representation, for bitwise operation is much more compact and efficient.

Comments

0

format(ord('\x11'), '08b') will get you 00010001, which should be close enough to what you want.

Comments

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.