-1

there is some strange while converting from INT to BYTES. the function i used to convert: (int).to_bytes(byte lenght,'big') in my specific cases i tried to convert 31 to Bytes, it showed:

b = (31).to_bytes(1,'big')
b
b'\x1f'

but when i convert the 10 or lager than 31. it will show another unexpected value:

b = (10).to_bytes(1,'big')
b
b'\n'
==> b value here supposed to be: b'\x0a'. i don't know why it return b'\n' please let me know the secret behind.

same with value 50.

b = (50).to_bytes(1,'big')
b
b'2'
==> b value supposed to be b'x\32'

Please help.....

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 2
    There is nothing wrong here. `b'\n'` means the same thing as `b'\x0a'`, and `b'2'` means the same thing as `b'\x32'`. The way Python represents the `bytes` object to you is just the canonical form. It's the same as how if you set `s = "hi"`, the value of `s` reported back to you is `'hi'` with single quotes instead of double. – Karl Knechtel Oct 10 '21 at 07:25

1 Answers1

1

Python represents bytes in such a way that if a value is printable ASCII, it will use that instead of an escape sequence. You can try it out:

>>> b'\x0a'
b'\n'
>>> b'\x32'
b'2'

And it checks out: \n is Python's escape sequence for newline (ASCII character 10), and 2 is ASCII character 50.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
  • Thanks Jasmijn. it's work. although it show b'2' but i sniff the package. the value still same b'\x32'. currently i'm using micropython to send bytes Over onther device. – Nhat Thanh Oct 11 '21 at 04:00