alixrx
alixrx

Reputation: 211

Convert char to hexadecimal by encoding in Java

For creating an EBU-STL file, I need to convert the chars into hexadecimal and then cast it to byte.

Like this:

String text = "This is a text";
char [] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
    (byte) chars[j]; // here I would like to convert the char to byte
}

The problem here is that I am looking for a way to convert the char with an encoding. For example, this greek character 'ω' (little omega), when I cast it to byte, it gives me -55 while I want 249 which is the encoding of Windows 1253.

So, how can I get a hexadecimal of a character in a specific encoding in java?

Upvotes: 0

Views: 444

Answers (1)

shubham4194
shubham4194

Reputation: 81

You can get the bytes encoded by a particular charset(Windows-1253) in the following way:

String text = "This is a text";
byte[] byteArray = text.getBytes("Windows-1253");

You can just loop over this byte array. It will give -7 for the character 'ω' which basically 249 (256-7).

Upvotes: 1

Related Questions