Why do we need the bitwise "and" for some char to byte conversions in Java?

Here I am working with a Java example translation in C #, which includes cryptography (AES and RSA, etc.)

At some point in the Java code (the one that really works and translates to C #), I found this piece of code:

for (i = i; i < size; i++) { encodedArr[j] = (byte) (data[i] & 0x00FF); j++; } // where data variable is a char[] and encodedArr is a byte[] 

After some googling ( here ), I saw that this is normal behavior mainly in Java code ...

I know that char is a 16-bit type, and byte is only 8 bits, but I could not understand the reason for this bitwise operation and the operation for converting char->byte .

Can anyone explain?

Thanks in advance.

+6
source share
3 answers

When you convert 0x00FF to binary, it becomes 0000 0000 1111 1111

When you and all with 1, it itself:

1 && 1 = 1, 0 && 1 = 0

When you and everything with 0, it's 0

1 && 0 = 0, 0 && 0 = 0

When this operation occurs encodedArr[j] = (byte) (data[i] & 0x00FF); It takes the last 8 bits and the last 8 bits of data only and saves them. It discards the first 8 bits and stores the last 8

The reason this is necessary is because a byte is defined as an eight-bit value. Bitwise and exists to stop potential overflow → IE by assigning 9 bits per byte

A char in Java is 2 bytes ! This logic is to stop the overflow. However, as someone remarked, this is pointless because the actor does it for you. Perhaps someone was careful?

+4
source

In this case, this is completely optional, but people seem to be "just in case". According to JLS, 5.1.3. Narrowing the primitive transform

Narrowing the conversion of char to an integral type T also simply discards everything except n low order bits, where n is the number of bits used to represent type T. In addition to the possible loss of information about the value of a numerical value, this can lead to a resulting value being a negative number although the characters are unsigned 16-bit integers.

Similar code is often needed in conversion extensions to suppress sign extensions.

+7
source

This is a way to truncate a value by storing only the least significant bits so that it "matches" in the byte!

Hope this helps!

+2
source

Source: https://habr.com/ru/post/988117/


All Articles