ByteArray
IfA bytearray is a mutable sequence of bytes (Integers where 0 ≤ x ≤ 255). You can construct a bytearray from a string (If it is not a byte-string, you wantwill have to manipulate bytesprovide encoding), I suggestan iterable of byte-sized integers, or an object with a buffer interface. You can of course just build it manually as well.
An example using bytearraysa byte-string:
string = b'DFH'
b = bytearray(string)
# Print it as a string
print b
# Prints the individual bytes, showing you that it's just a list of ints
print [i for i in b]
# Lets add one to the D
b[0] += 1
# And print the string again to see the result!
print b
The result:
DFH
[68, 70, 72]
EFH
This is the type you want if you want raw byte manipulation. They allowIf what you want is to deal with all theread 4 bytes as if they werea 32bit int, one would use the struct module, with the unpack method, but I usually just... bytes. Not strings shift them together myself from a bytearray. And, as
Printing the header in binary
What you seem to want is to take the name suggestsstring you have, they're made for that specific taskconvert it to a bytearray, and print them as a string in base 2/binary.
ASo here is a short example for how to write the header out in binary (I read random data from a file named "dump"):
After converting it to a bytearray, instead of having a string, you have a list of bytes. I thenI call bin() on every single one, which gives back a string with the binary representation we need, in the format of "0b1010". I don't want the "0b", so I slice it off with [2:]. Then, I use the string method zfill, which allows me to have the required amount of 0's prepended for the string to be 8 long (which is the amount of bits we need), as bin will not show any uneededunneeded zeroes.
If you're new to the language, the last line might belook quite mean. It uses list comprehension to make a list of all the binary strings we want to print, and then join them into the final string with spaces between the elements.