views:

110

answers:

2

I'm using python 3.1.1.

I know that I can create byte objects using the byte literal in the form of b'...'. In these byte objects, each byte can be represented as a character(in ascii code if I'm not wrong) or as a hexadecimal/octal number. Hexadecimal and octal numbers can be entered using an escape of \x for hexadecimal numbers and just a \ for octal numbers.

However, there's no escape sequences for decimal or binary numbers. Is there any way to enter them into byte objects?

+1  A: 

You could use binary literals for integers

>>> b = bytearray(b'abc')
>>> b[0] = 0b1001 # `9` decimal (TAB)
>>> b
bytearray(b'\tbc')
J.F. Sebastian
+2  A: 

You can use the built-in bytes constructor to turn a sequence of integers into a byte string:

>>> bytes((7,8,9,10,11))
b'\x07\x08\t\n\x0b'
>>> bytes(range(7,12))
b'\x07\x08\t\n\x0b'
>>> bytes((0b1,0b0,0b1))
b'\x01\x00\x01'
Ned Deily
Thanks! This is exactly what i was trying to do. I completely forgot about using these type of functions to initialise variables.
Eric