-1

I have a problem concerning the conversion from integer to bytes in Python 3. e.g:

a = 31
a.to_bytes(length=1, byteorder="little", signed=False)

will result in:

b'\x1f'

or

a = 155
a.to_bytes(length=1, byteorder="little", signed=False)

will result in:

b'\x9b'

So far so good. But e.g. with:

a = 46
a.to_bytes(length=1, byteorder="little", signed=False)

will result in:

b'.'

What did I do wrong? Or what is the problem here?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • `assert b'.' == assert b'\x2e'`. – chepner Jan 26 '22 at 15:53
  • Get familiar with the [ASCII table](https://www.asciitable.com). 0-31 are invalid characters. Anything over 127 is out of range. Anything in between 32 and 127 is a valid ASCII represented with an hex code. So the bytes in this range are presented as their ASCII values – Tomerikoo Jan 26 '22 at 16:09

3 Answers3

0

b'.' is correct - it just so happens that the number 46 represents a full stop instead of an invalid character so it is not shown as b'\x...'

Lecdi
  • 2,189
  • 2
  • 6
  • 20
0

From 0~31, and 127~255, there are no nice shorter ASCII char for it, therefore it's using the hex string, and from 32~126, each number has a nice ASCII char mapping to it, therefore it prefers to use that shorter ASCII char to represent the byte, instead of the hex value of the number.

Lingchao Cao
  • 467
  • 6
  • 11
0

The . is the ASCII form of 46. You can use hex() method to see it:

In [38]: b".".hex()
Out[38]: '2e'
Mathieu Longtin
  • 15,922
  • 6
  • 30
  • 40