Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing char as a byte in Java

Tags:

I must convert a char into a byte or a byte array. In other languages I know that a char is just a single byte. However, looking at the Java Character class, its min value is \u0000 and its max value is \uFFFF. This makes it seem like a char is 2 bytes long.

Will I be able to store it as a byte or do I need to store it as two bytes?

Before anyone asks, I will say that I'm trying to do this because I'm working under an interface that expects my results to be a byte array. So I have to convert my char to one.

Please let me know and help me understand this.

Thanks, jbu

like image 608
jbu Avatar asked Mar 30 '09 22:03

jbu


People also ask

How do I convert a char to a byte?

Syntax: byte by = (byte) ch; Here, ch is the char variable to be converted into Byte. It tells the compiler to convert the char into its byte equivalent value.

What is the byte of char in Java?

A byte is 8 bit . char is 16 bit .

Is a char one byte in Java?

Every character type in Java occupies 2 bytes in size. For converting a String to its byte array equivalent we convert every character of the String to its 2 byte representation.


1 Answers

To convert characters to bytes, you need to specify a character encoding. Some character encodings use one byte per character, while others use two or more bytes. In fact, for many languages, there are far too many characters to encode with a single byte.

In Java, the simplest way to convert from characters to bytes is with the String class's getBytes(Charset) method. (The StandardCharsets class defines some common encodings.) However, this method will silently replace characters with � if the character cannot be mapped under the specified encoding. If you need more control, you can configure a CharsetEncoder to handle this case with an error or use a different replacement character.

like image 121
erickson Avatar answered Dec 21 '22 23:12

erickson