Waseem
Waseem

Reputation: 1408

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 ???

Upvotes: 6

Views: 14678

Answers (2)

anubhava
anubhava

Reputation: 785156

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.

Upvotes: 12

Sunil Kumar B M
Sunil Kumar B M

Reputation: 2795

ANDing with 0x00FF retains only the last 8 significant bit and zeros others bits.

E.g.:
0xD2A5 & 0x00FF = 1101001010100101 & 0000000011111111 = 0000000010100101 = A5

Upvotes: 2

Related Questions