Reputation: 573
In attempting to communicate with a stepper motor controller over a serial port with pyserial I am receiving something like this as a response '/0\x03\r\n'
.
I need to be able to convert the '\x03'
byte to binary, the part that has me confused is that and '\x03'
is considered a single character of the string so I can't do anything like: '\x03'[2:]
to get '03'
.
How can I convert '\x03'
to something usable such as: 00000011
or '03'
?
Upvotes: 1
Views: 465
Reputation: 1122022
\x03
is Python's way of telling you that there is one byte at that part of the string that has a hexadecimal value of 03
, which is not a printable character. The first two characters are printable (hex 2F and hex 30, respectively, ASCII characters /
and 0
) so Python used the ASCII characters they correspond with.
You can use ord()
to turn that into an integer:
>>> ord('\x03')
3
You could use the bin()
function, or the format()
function to turn that integer into a binary representation, with the format()
function being the more flexible and versatile option:
>>> bin(3)
'0b11'
>>> format(3, 'b')
'11'
>>> format(3, '08b')
'00000011'
Upvotes: 4
Reputation: 76194
Try using ord
to get each character's numerical value.
>>> s = '/0\x03\r\n'
>>> [ord(c) for c in s]
[47, 48, 3, 13, 10]
>>> [ord(c) for c in s][2]
3
Upvotes: 0