1

I'm using to_bytes() to convert an 128-bit unsigned value to bytes:

>>> hex(a)
'0xd8cdb78070b4c55a818665aa0d02dfda'

>>> a.to_bytes(16, "big")
b'\xd8\xcd\xb7\x80p\xb4\xc5Z\x81\x86e\xaa\r\x02\xdf\xda'

But not all bytes displayed above are correct, there are "\x80p", "\xc5Z" and weirdly just "\r". The bytes are actually correct, as can be shown like this:

>>> hex(int.from_bytes(a.to_bytes(16, "big"), "big"))
'0xd8cdb78070b4c55a818665aa0d02dfda'

But when the Cpython interpreter display the result from the to_bytes() operation some bytes are converted to their ASCII character. For example, the byte value 0x70 is converted to 'p'. Is there are way to get Cpython to display the bytes as \x no matter what the NN value is?

This happens using: Python 3.7.6 (default, Dec 30 2019, 19:38:28) [Clang 11.0.0 (clang-1100.0.33.16)] on darwin

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • This is default behavior of Python and cannot be changed. You can write your own Python code to format the bytestring in any way you want of course. – wovano Feb 09 '20 at 10:06
  • And here is some background on `b'...'`: https://stackoverflow.com/questions/16862497/python-bytes-literal-has-extra-characters-that-arent-hex-but-alter-the-value-o/16862839#16862839 – Jongware Feb 09 '20 at 10:07
  • @usr2564301 Your first link provides work arounds similar to those I've created. But they are work arounds with for example loops. I was more interested in getting Python to not be smart about the values. Your second answer gave a good background. Thanks! – Joachim Strömbergson Feb 09 '20 at 11:03

0 Answers0