I checked a lot on the Internet and used struct for packaging and package settlement. please google the content, but it is not the result I want, I just want to directly convert a string into byte []. I don't need to define every location so strictly. I found that python2.6 has directly supported binary Arrays:
As it is not very clear, the test is as follows:
>>> S1 = "People's Republic of China" >>> S1 '\ xd6 \ xd0 \ xbb \ xAA \ xc8 \ xcb \ xc3 \ xf1 \ xb9 \ XB2 \ Xba \ XCD \ xb9 \ xfa '>>> list (S1) ['\ xd6', '\ xd0',' \ xbb ',' \ xAA ',' \ xc8 ',' \ xcb ',' \ xc3 ', '\ xf1', '\ xb9',' \ XB2 ',' \ xba', '\ xcd',' \ xb9 ', '\ xfa']> S2 = B "People's Republic of China"> S2 '\ xd6 \ xd0 \ xbb \ xAA \ xc8 \ xcb \ xc3 \ xf1 \ xb9 \ XB2 \ xba \ XCD \ xb9 \ xfa '> List (S2) ['\ xd6', '\ xd0',' \ xbb ',' \ xAA ',' \ xc8 ',' \ xcb ',' \ xc3 ', '\ xf1', '\ xb9',' \ XB2 ',' \ xba', '\ xcd',' \ xb9 ', '\ xfa'] >>> S3 = u "People's Republic of China" >>> s3u' \ xd6 \ xd0 \ xbb \ xAA \ xc8 \ xcb \ xc3 \ xf1 \ xb9 \ XB2 \ xba \ XCD \ xb9 \ xfa '> List (S3) [U' \ xd6 ', U' \ xd0', U' \ xbb ', U' \ xAA', U' \ xc8 ', U' \ xcb ', u' \ xc3', U' \ xf1 ', U' \ xb9', U' \ XB2', U' \ Xba ', U' \ XCD ', u' \ xb9', U' \ xfa ']> S4 = bytearray ("People's Republic of China")> s4bytearray (B '\ xd6 \ xd0 \ xbb \ xAA \ xc8 \ xcb \ xc3 \ xf1 \ xb9 \ XB2 \ Xba \ XCD \ xb9 \ xfa')> list (S4) [214,208,187,170,200,203,195,241,185,178,186,205,185,250] >>## demonstrate changing byte to sbyte >>>> S5 = [I if I <128 else i-256 for I In S4] >>> S5 [-42, -48,-69,-86,-56,-53,-61,-15,-71,-78,-70,-51,-71, -6] >>>>>> type (S1) <type 'str' >>>> type (S2) <type 'str' >>>> type (S3) <type 'unicode '>>>> type (S4) <type 'bytearray' >>> type (S5) <type 'LIST' >>>>
TIPS: In the above example, the List ing and "ternary expression" are used to convert byte to sbyte. Of course, there is no ternary expression in Python, so the syntax I use is if Else,
Of course, the flexible combination of and-or can also achieve the same effect:
S5 = [I <128 and i-256 or I for I In S4] # There is a bug here, that is, an error occurs when I is zero and 256, since 256 does not appear, then 0 is processed: S5 = [I <128 and I! = 0 and i-256 or I for I In S4]
Of course, this requires a deep understanding of the and-or system syntax.