holmis83
holmis83

Reputation: 16644

Python String to Java byte[]

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.

Upvotes: 5

Views: 3020

Answers (2)

dsh
dsh

Reputation: 12214

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)

Upvotes: 0

holmis83
holmis83

Reputation: 16644

I found an utility method that does the trick:

from org.python.core.util import StringUtil
myJavaArr = StringUtil.toBytes(myStr)

Upvotes: 5

Related Questions