Utsab
Utsab

Reputation: 209

how to find least significant byte of an integer in Java?

I need help with the following problem:

Write an expression that results in the least significant byte of an integer x being set to 0, but all other bits unchanged. For example: 0x98234493 becomes 0x98234400.

I am confused on how to access the least significant byte.

public static int Q3(int x) {
    return (x & 0xFFFFFFFF);
}

What am i doing wrong?

Upvotes: 0

Views: 2405

Answers (3)

Omolola Olamide
Omolola Olamide

Reputation: 9

The solution will be

public static int Q3(int x) {
    return (x & OxF);
}

Upvotes: 0

EntangledLoops
EntangledLoops

Reputation: 2119

If all you want is the least significant byte of an integer (as your question is stated), then it's very simple:

byte b = (byte) (x & 0xFF);

This works because all the high bits of 0xFF will be set to 0 by default, so you are masking out everything but the bottom byte. A byte is 8 bits and each 'F' is 4 bits (written in hexadecimal). In binary, an F is 1111, so FF masks out everything but the bottom 8 bits.

Upvotes: 1

J...S
J...S

Reputation: 5207

You could do

public static int Q3(int x) {
    return (x & ~255);
}

255 in binary would have all the bits in the least significant byte set while all others are zero.

Therefore ~255, which is the complement of 255, will have all bits except those in the least significant byte set while all bits of the least significant byte are zeros.

This ~255 can be &ed with the input number n to set all bits in the least significant byte to zero while the other bits remain unchanged.

Upvotes: 0

Related Questions