-4

I have been searching for a while how to convert string in python to array of signed and unsigned bytes and to reverse the bytearray into string again.

For eg:

s = "sample data"  # for example any string

bytearray = [8, 28, 61, 26, 124, -4, -27, 87, -99, -13, 94, 115, 23, 85, -5, 123, 52, 93, -127, 75, 79, -100, -75, 126, -51, 45, 91, 46, -114, -66, -18, -26, -123, 34, -110, -60, 39, 100, 109, -95, -8, 29, -20, 13, -22, -116, 86, -27, 97, -56, -115, 28, 68, 8, 50, 63, 105, 77, 68, -86, 63, -8, 59, -59, 91, 48, 2, 82, 65, 118, -107, -88, 49, 65, 5, -27, -16, -61, 8, 47, 76, -110, -46, 71, 80, 70, 108, -115, -101, 29, -32, -34, 100, -101, -108, -42, 76, -56, -45, 39, 25, 59, 45, 17]
# should give array of signed and unsigned bytes
marmeladze
  • 6,468
  • 3
  • 24
  • 45
Neeshu
  • 1
  • 1
  • Why would a string (with, say, ASCII or UTF-8 encoding) result in negative numbers? (I think bytes are by definition unsigned.) – 9769953 Mar 12 '20 at 08:12
  • How does your "sample data" string relate to your example `bytearray`? – 9769953 Mar 12 '20 at 08:12
  • 1
    Does this answer your question? [Python: convert string to byte array](https://stackoverflow.com/questions/11624190/python-convert-string-to-byte-array) – 9769953 Mar 12 '20 at 08:13
  • Why does your question title mention "unsigned byte array", yet the actual text mentions "signed and unsigned bytes"? Which one is it? – 9769953 Mar 12 '20 at 08:14
  • StackOverflow is not a code-writing service. Please read through the [Help Center](https://stackoverflow.com/help), in particular [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) If you run into a specific problem, research it thoroughly, search thoroughly here, and if you're still stuck post your code and a description of the problem. Also, remember to include [Minimum, Complete, Verifiable Example](https://stackoverflow.com/help/mcve). People will be glad to help – Andreas Mar 12 '20 at 08:15
  • i have specified Unsigned Byte array in python because im not able to get unsigned bytes of string. i can change given string to byte array but they all are signed , i need both signed and unsigned bytes of a given string – Neeshu Mar 12 '20 at 08:30

1 Answers1

0

Python doesn't have bytes per-se, and its "bytes" are always unsigned in the sense that they're int between 0 and 255.

If you want "signed bytes" you need to request such parsing explicitly using the struct or array modules (typecode b).

Masklinn
  • 34,759
  • 3
  • 38
  • 57