3

I'm trying to convert a ushort to bytes. However, when I try this:

>>import struct
>>val =struct.pack('<H',10000)
b"\x10'"

Instead of:

b'\x10\x27'

Is this a bug? Or I am just doing something silly?

I'll be writing this data to a serial device.

Thanks in advance.

Kucosyn
  • 49
  • 6
  • 1
    `b"\x10'"` and `b'\x10\x27'` are the same thing. `b'\x27' == b"'"`. Try `print(b'\x10\x27')` and you'll get `b"\x10'"` as output. – Aran-Fey Sep 08 '17 at 15:23
  • Just a follow-up, won't it have any negative effects when I try to write that for serial communication? I had an issue before in one of my projects where the microcontroller just stops responding once we send a value like "50" into it. Thanks again, @Rawring – Kucosyn Sep 08 '17 at 15:28
  • There are no negative effects because it is *the same thing*. `b'\x27'` and `b"'"` are **identical**. They are just two different things to write the same thing. Like you can write `0xA`, `0o12`, or `10` to refer to the same number. – poke Sep 08 '17 at 15:33
  • Thanks for the help, @poke. I wasn't familiar with data structures that's why I thought I was missing out something with my code. – Kucosyn Sep 08 '17 at 15:36

1 Answers1

2

It's an alternate representation for \x27:

>>> hex(ord("'"))
'0x27'

You won't have any problems converting back to the int representation:

>>> int.from_bytes(b"\x10'", 'little')
10000
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks, @Moses. I was just worried it would cause problems when I try to use write data for serial communication. – Kucosyn Sep 08 '17 at 15:33