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.

asked Jan 14, 2013 at 2:54

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
answered Jan 14, 2013 at 3:00
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.

answered Jan 14, 2013 at 7:05

Comments

0

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

answered Jan 14, 2013 at 7:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.