Issue
I have tried several ways to convert this Java instruction to python, but I always get some error or wrong outputs. What is the correct way to do it?
String x = new String(new byte[]{(byte) 23353, (byte) 333, (byte) 614537057});
(x is equal to string "9Ma")
I tried x = bytes([23353, 5682, 10310]).decode('utf-8')
But the result is: ValueError: byte must be in range(0, 256)
Solution
As the error says, you can't pass values larger than 255
to the bytes()
function.
However, you can pass the %256
value:
byte_values = [23353, 333, 614537057]
x = "".join(chr(value % 256) for value in byte_values)
print(x)
The above code prints 9Ma
on my side.
However, I'd suggest you to functionally verify the sense of what your Java code is doing because it is shortcutting the above conversion from int
to byte
instead of directly producing the correct bytes.
Answered By - Matteo NNZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.