# Bit operatation question

Dar Var
Ranch Hand
Posts: 74
Hi I need help understanding some code. The code is used to convert a byte to a hexadecimal.

When converting from a byte to an int why do you have to do a logical AND with 0xFF.

For example:
int i = 'A' & 0xff;

Also what will the following operation do. I know it does a right shift of 4 bits but what is the resulting. The code converts the character to hex but I am unclear as to how it does it.

(i >> 4);
(i & 0xf);

examples using bit patterns would be helpful tanx.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
When converting from a byte to an int why do you have to do a logical AND with 0xFF.

For example:
int i = 'A' & 0xff;

First of all, in that line of code there is no conversion from a byte to an int. The 'A' is a character literal (its type is char, not byte). The 0xff is an integer literal. Also, the AND operator & is not a logical AND, it is a bitwise AND. The logical AND operator is &&.

Doing a bitwise AND with 0xff means keeping the lower 8 bits and clearing all higher bits.

About the second question: You first shift i four bits to the right and with the & operation you keep the lower 4 bits and mask the rest off.

In hexadecimal, each digit represents 4 bits in the value. Take for example the value 156 (decimal). In binary, this is: 10011100. It is easy to convert this to hexadecimal: split the binary number into groups of 4 bits: 1001 1100. Each group of 4 bits corresponds to 1 hexadecimal digit. 1001 = 9 and 1100 = C, so 156 = 10011100 = 0x9C. See this: Hexadecimal (Wikipedia)

kirba devi
Ranch Hand
Posts: 50
Hi Young,
Doing a bitwise AND with 0xff means keeping the lower 8 bits and clearing all higher bits.

int n='A' & 0xff;

Havent understood by the above quote.
Can you explain me with some example

Regards
Kirba.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
Look at the logic table for the AND operation:

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

Notice the following: The result is 1 when both bits are 1, otherwise the result is 0.

Suppose you have a value, and you want to keep the lower 8 bits of the value, and set all the other bits of the value to 0. You can do this by doing a bitwise AND operation, where you AND the value with a mask in which you set the bits you want to keep to 1, and the bits you want to clear to 0.

For example:

Note that bits 8-31 are 0 in the result, and bits 0-7 contain the lower 8 bits of the original value.