Convert object 'bytes' to string

I tried to find a solution but still stuck with it. I want to use PyVisa to control a function generator. I have waveform

which is a list of values โ€‹โ€‹between 0

and 16382

Then I have to prepare it such that each point waveform

takes 2 bytes. The value is in big-endian, MSB-first format and is direct binary. So I do binwaveform = pack('>'+'h'*len(waveform), *waveform)

And then when I try to write it to the instrument with AFG.write('trace ememory, '+ header + binwaveform)

, I get the error:

  File ".\afg3000.py", line 97, in <module>
    AFG.write('trace ememory, '+ header + binwaveform)
TypeError: Can't convert 'bytes' object to str implicitly

      

I tried to solve it with AFG.write('trace ememory, '+ header + binwaveform.decode())

, but it looks like it tries to use ASCII characters by default, which is wrong for some values:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 52787: invalid start byte

Could you help me?

+3


source to share


1 answer


binwaveform

is a packed array of integer bytes. For example:

struct.pack('<h', 4545)
b'\xc1\x11'

      

You cannot print it as it doesn't make any sense to your terminal. In the above example, 0xC1

ASCII and UTF-8 are invalid.

When you add a byte string to a regular string ( trace ememory, '+ header + binwaveform

), Python wants to convert it to readable text, but doesn't know how.



The decoding assumes that the text is not.

Your best bet is to print the hexadecimal representation:

import codecs
binwaveform_hex = codecs.encode(binwaveform, 'hex')
binwaveform_hex_str = str(binwaveform_hex)
AFG.write('trace ememory, '+ header + binwaveform_hex_str)

      

+2


source







All Articles