Reputation: 23
I want to send out a bytearray using serial module. Elements in the bytearray are float data types that are rounded and converted to integers, for this reason I use numpy for speed efficiency rather than pythons native data type conversion functions. Problem is numpy is incorrectly representing decimal integers 9, 10, and 13 inside bytearray. I'm using python 3.4.2 and numpy 1.9.2 on Windows 7 x64.
Here is example of problem:
import numpy
>>> x = bytearray([])
>>> for i in range(20):
x.append(numpy.int16(i))
>>> x
bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13')
decimal integers 9, 10, 13 become t, n, and r when they should be represented as 0x09, 0x0a, 0x0d
Upvotes: 0
Views: 113
Reputation: 74655
The values are actually correct. What you are seeing is how the printing which calls repr
on the object formats those as bytes as escape sequences. \n
is the same as \x0a
as 0a
is 10
. \n
is chosen over \x0a
as it is shorter and more easily recognized.
Now if you want to print the bytes as hex as in 45
rather than \x45
use the binascii.hexlify
function to convert before printing.
Upvotes: 1