1

I want to know how can I convert an integer into hex format \x

Ffor example:

input = 62

---conversion---

output = \x3E

when I do a simple hex(int) i get 0x3e and that is ok, but the thing is, I have a bytearray which looks like this:

b'\x14\xFF\x81\x83\x06\x08\x00\x0F\x00'

and I want to append the he value of int to it, so it looks like this:

b'\x14\xFF\x81\x83\x06\x08\x00\x0F\x00\x3E'

I've tried to convert it to byte and append it afterwards but I get a result like:

b'\x14\xFF\x81\x83\x06\x08\x00\x0F\x00>'
Drise
  • 4,310
  • 5
  • 41
  • 66
  • 1
    `b'\x14\xFF\x81\x83\x06\x08\x00\x0F\x00>'` is correct - `>` is ASCII 0x3E. There's probably a good dupe around here somewhere. – user2357112 Mar 19 '18 at 18:09
  • 2
    There is nothing to convert, those escape sequences are the correct representation of the value you wanted. Any codepoint that can be shown as a printable ASCII character is represented as such. 3E is the codepoint for `>`. – Martijn Pieters Mar 19 '18 at 18:11
  • If you want to see the actual hex values inside a `bytes` or `bytearray`, there are simple ways to do it for pretty much any reasonable format you can come up with, but just using the `repr` is generally not answer. – abarnert Mar 19 '18 at 18:14
  • If performance isn't an issue, for output to myself, I usually like to be as explicit as possible about what I'm printing out so I can modify it easily, like `''.join(f'\\x{ch:02X}' for ch in b)`. For output I definitely _don't_ want to change later, of course, I'd use a nice stdlib function. Either way, `print` that, and you'll see `\x14\xFF\x81\x83\x06\x08\x00\x0F\x00\x3E`, which is (I think) exactly what you want here, right? And that's how you verify that you added the right data after all. – abarnert Mar 19 '18 at 18:18
  • yeah, about that.. Performance is issue. this should be used for live calculating CRC16. I just wanted to know if there is a way to make it look nice :) :) – Edo Spahić Mar 19 '18 at 18:23
  • What you see here is Python's default representation of a byte array. If you don't like it, write your own. (Which is not meant to be harsh. You may already be doing that even for a simple object such as a text string. After all, `'this is a string\n'` doesn't look "nice" either – at the very least you'd want to lose the quotes!) – Jongware Mar 19 '18 at 18:38

0 Answers0