E
E
EEElice2019-07-09 16:16:11
Python
EEElice, 2019-07-09 16:16:11

How to convert a byte string to a normal one?

I have a byte string like this:

b'&\t\x07\x1c\xa8\xcd\x85\xffRmfy\xe5\xd2_\xd7\xb4)\xad\xd2'

It should come out of something like this:
26 09 07 1c a8 cd 85 ff 52 6d 66 79 e5 d2 5f d7 b4 29 ad d2
#пробелы не обязательны

As you can see, some of the bytes have been converted to "byte characters"
>>> b'\x26'==b'&'
True

Right off the bat, this is throwing an error:
SomeString.decode('utf-8')
#Выкидывает ошибку на байте b'\xa8'

How to solve the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
SagePtr, 2019-07-09
@EEElice

https://docs.python.org/3.5/library/binascii.html#...

R
Roman Kitaev, 2019-07-09
@deliro

In [1]: b'&\t\x07\x1c\xa8\xcd\x85\xffRmfy\xe5\xd2_\xd7\xb4)\xad\xd2'[0]                                                 
Out[1]: 38

In [2]: for b in b'&\t\x07\x1c\xa8\xcd\x85\xffRmfy\xe5\xd2_\xd7\xb4)\xad\xd2': 
   ...:     print(b) 
   ...:                                                                                                                 
38
9
7
28
168
205
133
255
82
109
102
121
229
210
95
215
180
41
173
210

In [3]: for b in b'&\t\x07\x1c\xa8\xcd\x85\xffRmfy\xe5\xd2_\xd7\xb4)\xad\xd2': 
   ...:     print(hex(b)) 
   ...:                                                                                                                                                               
0x26
0x9
0x7
0x1c
0xa8
0xcd
0x85
0xff
0x52
0x6d
0x66
0x79
0xe5
0xd2
0x5f
0xd7
0xb4
0x29
0xad
0xd2

A
Alexander, 2019-07-09
@NeiroNx

in_str = b'&\t\x07\x1c\xa8\xcd\x85\xffRmfy\xe5\xd2_\xd7\xb4)\xad\xd2'
out_str = " ".join([ "%02X"%x for x in in_str])
'26 09 07 1C A8 CD 85 FF 52 6D 66 79 E5 D2 5F D7 B4 29 AD D2'

If spaces are not needed, then remove the space from the quotes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question