Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert char to byte?

I was studying an open source code where I came across the following line

stringBytes[i] = (byte) (stringChars[i] & 0x00FF);

Can someone explain what is actually happening in this line ???

like image 453
Waseem Avatar asked Feb 04 '12 08:02

Waseem


People also ask

How many bytes is 32 characters?

A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

How many bytes is 2000 characters?

Think about how many bits and Bytes might exist on a Word document. How many bits are there in a single 2,000 character document? **Quick Test: Let's say that there are 2,000 characters in the document. Answer: In this example, 2,000 characters x 1 Byte per character = 2,000 Bytes x 8 bits =16,000 bits.

Is byte same as char?

3) Another difference between char and byte is that char is a larger data type than a byte. The range of byte is between -128 to 127 but the range of char is from 0 to 65535 because a byte is a signed 8-bit data type and char is an unsigned 16-bit data type hence, its maximum value is 2 ^ 16 - 1 which is 65535.


1 Answers

Char consists of 2 bytes in Java and of course byte is single byte.

So in this operation:

stringBytes[i] = (byte) stringChars[i] & 0x00FF

A char value (16 bits) is being binary ANDED with number 0x00FF (binary: 0000 0000 1111 1111) to make it one byte.

By binary ANDING with 8 0s and 8 1s you're basically masking off 8 left most OR most significant bits (MSB) of the char value thus leaving only 8 right most or least significant bits (LSB) intact. Then code is assigning resulting values to a byte by using cast (byte), which is otherwise an int value.

like image 120
anubhava Avatar answered Sep 22 '22 16:09

anubhava