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

0

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?

bitwise-operators
bit-shift
asked on Stack Overflow Sep 5, 2017 by Utsab

3 Answers

0

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.

answered on Stack Overflow Sep 9, 2017 by J...S
0

The solution will be public static int Q3(int x) { return (x & OxF); }

answered on Stack Overflow Jan 30, 2018 by Omolola Olamide
0

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.

answered on Stack Overflow Sep 29, 2019 by EntangledLoops

User contributions licensed under CC BY-SA 3.0