1

I am trying to understand one of the python function called bytearray(). Adding a decimal value to this object will give you hex representation of bytearray. But in the range of 33-126 its giving ASCII character representation of bytearray. So problem here is if i construct a bytearray in python and send to our other module of the project which written in C-language, so what will they expect from that bytearray representation, is it will be complete hex representation or mix of something ?

Example-1:

s = bytearray()
s.append(10)
print(s)  # bytearray(b'\n') . What kind of representation it is?

Example-2:

s = bytearray()
s.append(20)
print(s)  # bytearray(b'\x14') . hex representation 

Example-3:

s = bytearray()
s.append(20)
print(s)  # bytearray(b'$') . ASCII representation 

Can somebody explain what is the reason behind this?

Vivek Kumar
  • 159
  • 3
  • 13
  • I have no sources, but this gives the best possible human-readable version of a byte array. When it is a non-printable character, it either gives a well-known escape sequence, or a hex notation. – Bart Friederichs Jul 14 '20 at 11:48
  • *"so what will they expect from that bytearray representation"* — That depends on how you send the array. If you send it via a socket or such to C, it will receive *the bytes*. The actual bytes. Not the string representation of them or a hex representation, but… *the bytes*. – deceze Jul 14 '20 at 12:26
  • @deceze can i say bytearray() output will be bytes representation . And hex representation and bytes representation both are different things . – Vivek Kumar Jul 14 '20 at 12:30
  • There's a difference between the bytes and their representation. You're never actually seeing the raw bytes. The raw bytes are voltage fluctuations in hardware. You can't see that, so you're always looking at some abstract representation of it. They can be represented in many different forms, including hex notation and ASCII characters. When you send the actual raw bytes to C, it receives actual raw bytes. If you turn those bytes into some representation like a hex sequence (so, ASCII values of a hex representation of the bytes, themselves actually bytes), then that's what you'll get. – deceze Jul 14 '20 at 12:39

0 Answers0