0

I have a function I am mapping from Javascript:

var commandBytes = [4,1,0,0,0,0, Math.floor(224 + (52/16)), 52 % 16];

...this is how I have in Python:

data = bytearray([4,1,0,0,0,0, 224 + 52 // 16, 52 % 16])

...this is what the output looks like in IDLE:

bytearray(b'\x04\x01\x00\x00\x00\x00\xe3\x04')

...this is what the original output looks like when output by Javascript to the Command Prompt window:

<Buffer 04 01 00 00 00 00 e3 04>

...first issue I have is the bytes in IDLE seem to be printed in hex rather than actual numbers. Second is, even though I know my connection to the machine I am passing the command to is good as I am getting a response, the command itself does not work.

What do I need to change so that my Python output replicates my Javascript output?

Thanks

2
  • 1
    Why do you care how it is displayed on your terminal - it looks like it has equivalent data. If you really want it to display the same then extend the bytearray() and implement your own __str__() and/or __repr__(). You haven't provided enough information to help with why the command isn't working. Commented May 26, 2018 at 19:42
  • What exactly are you trying to replicate? What are "actual numbers"? Why is formatting and issue? I don't really understand your question here. Commented May 26, 2018 at 19:57

1 Answer 1

1

You can easily change how it is printed, either by creating your own print_function or by extending bytearray and implementing __str__() and/or __repr__(), e.g.:

class ByteArray(bytearray):
    def __str__(self):
        return '<Buffer {}>'.format(' '.join(format(x, '02x') for x in self))

In []:
b = ByteArray([4,1,0,0,0,0, 224 + 52 // 16, 52 % 16])
print(b)

Out[]:
<Buffer 04 01 00 00 00 00 e3 04>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.