From what I have understood, A Python 2 string (type str
) is nothing but a sequence of bytes. How do I convert such a string to a Java byte array, explicit?
A naive attempt that doesn't work:
from jarray import array
myStr = 'some str object'
myJavaArr = array(myStr, 'b') # TypeError: Type not compatible with array type
My reason to this is that when Jython implicitly converts a Python String to Java code, it converts it to a Java String, incorrectly because it doesn't know the encoding of the str
.
Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.
Definition and Usage. The byte keyword is a data type that can store whole numbers from -128 to 127.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.
I found an utility method that does the trick:
from org.python.core.util import StringUtil
myJavaArr = StringUtil.toBytes(myStr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With