I am using Pyserial to write out bytes to a connection.
One of the things I have been struggling with is figuring out how to write out exactly the bits that I want. I have had success writing out the bytes of a strings ascii form, such as
variable = 'h'.encode()
serial.write(variable)
And that will write out the bits of H succesfully. However if I do something like that with b'\b001' it won't write out 001 like I had hoped it would.
Is there a way to do this so I can simply define variables using 1 and 0 and then use the write function.
I tried also defining like this:
y = 0x13
out = s.write(y)
Which according to the write function's documentation, the function returns the amount of bytes written. When I ran this specific code it returned 19
If I understand correctly you are trying to find a way to send binary data as python bytes objects, and hex data as python bytes objects (in the second part).
it may be counter intuitive, but pythons
b''
syntax doesn't stand for binary, but bytes hence whyb'0010101'
doesn't work like you want.Bytes accepts hex data as bytes by default, to do this, you need to format the hex data as
b'\xFF\x04'
. For exampleThis can then be sent over pyserial. To do binary you'll need to use python
int
's construction methods, ie theint(number, base)
method.This is further explained here
but this can basically be done via
Unfortunately that only works for binary strings of size 8 bits (and it will give you an error telling you so). In order to get around this, you can do the following:
little endian is least significant byte in smallest address (ie index 0) big is opposite
Be careful of the larger binary integer method, I'm not sure what python does internally to convert binary to an integer, but for arbitarily large binary data I would suspect slow down due to how I would niavely implement the conversion. I'll give you an example of why in how I would do the binary to unsigned integer conversion:
It might not be quite obvious at first, but because python ints are arbitraily sized eventually you are going to get to the point where you are adding very large ints together, outside of typical arithmetic int size (ie larger than 64 bits). This means that over time with large binary values (which you will likely produce) you are going to get non linear time complexity as N increases the size in bytes of the additions will as well as they grow outside of 64 bits (and more processing will need to be done to carry out the addition, which will be O(n_bytes)) instead of O(1))
To solve this you would just need to make a function that separates the binary values before converting to bytes with them (like
binary_to_bytes(binary_string)
)