简体   繁体   中英

How to mask byte value in Java?

My problem is some like this.

I have some calculation in byte in Java. In some calculation I get my desired result "2a" in byte value but in some calculation I get "ffffff9a" in byte value. I just want the "9a" value in from the result "ffffff9a". I tried this but didn't work.

byte a = (byte) b & 0xff;

where b have value "ffffff9a" byte value.

But while displaying the same process works like

System.out.println(Integer.toHexString(b & 0xff));

Where am I going wrong? What can I do to get my desired value?

Thanks


Actually I am trying to convert 8 bit character into gsm 7 bit. Also if someone there can help me through this, it would be helpful too. String is stored as a byte array and I have to convert this string or 8 bit bytes into 7 bit.

The byte type in Java is signed . It has a range of [-128, 127].

System.out.println(Integer.toHexString(a & 0xff)); // note a, not b

Would show "the correct value" even though a , which is of type byte , will contain a negative value ( (byte)0x92 ). That is, (int)a == 0x92 will be false because the cast to int keeps the value, negative and all, while (a & 0xff) == 0x92 will be true. This is because the bit-wise & promotes the expression to an int type while "masking away" the "sign bit" (not really sign bit, but artefact of two's complement).

See: Java How To "Covert" Bytes

Happy coding.

Your initial code was: byte a = (byte) b & 0xff;

The (byte) typecast only applied to the b , which is already a byte . The & operator then widened that to an int so you got the result "ffffff9a" from the int .

You need to ensure that you typecast applies to the result of the & , not just to its first operand:

byte a = (byte)(b & 0xff);

Note the extra pair of parentheses.

//bit is zero base
public static boolean isSet(byte value, int bit)
{
    int b = (int)value & 0xff;
    b >>= bit;
    b &= 0x01;
    if( b != 0 )
    {
        return true;
    }
    return false;
}
public static byte setBit(byte value, int bit)
{
    int b = (int)value;

    b |= (1 << bit);
    return (byte)(b & 0xff);
}
public static byte clearBit(byte value, int bit)
{
    int b = (int)value;

    b &= ~(1 << bit);
    return (byte)(b & 0xff);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM