5

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.

2 Answers 2

5

I found an utility method that does the trick:

from org.python.core.util import StringUtil
myJavaArr = StringUtil.toBytes(myStr)
Sign up to request clarification or add additional context in comments.

Comments

0

Your original approach of passing a str object to jarray.array() worked in Jython 2.5 and earlier.

Now you must convert the str to a sequence of numbers first (eg list, tuple, or bytearray):

myStr = 'some str object'
myJavaArr = array( bytearray(myStr), 'b')

or

myStr = 'some str object'
myList = [ord(ch) for ch in myStr]
myJavaArr = array( myList, 'b')

(see also https://sourceforge.net/p/jython/mailman/message/35003179/)

Note, too, that Java's byte type is signed. The conversion will fail if any of your integers have a value outside the range -128..127. If you are starting with unsigned byte values in Python, you'll need to convert them. (eg apply this to each value: if 0x80 <= i <= 0xFF: i = i - 256)

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.