Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String to Java byte[]

Tags:

jython

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.

like image 348
holmis83 Avatar asked Aug 21 '15 13:08

holmis83


People also ask

Is byte [] same as string?

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.

What is byte [] in Java?

Definition and Usage. The byte keyword is a data type that can store whole numbers from -128 to 127.

How do you turn a string into a byte?

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.


1 Answers

I found an utility method that does the trick:

from org.python.core.util import StringUtil
myJavaArr = StringUtil.toBytes(myStr)
like image 93
holmis83 Avatar answered Jan 01 '23 09:01

holmis83