简体   繁体   中英

Java, store in byte higher value than 127

For an assignment I get some bytes, make some calculations on their Binary values and have to return that calculated Stuff in a Byte Array.

My Problem is now, that byte only stores up to 127, but my values can be up to 2^8-1 (11111111). I already tried to convert it to hex, but it´s of course not working either.

So, is that possible, if yes how, or is that exercise not possible like that?

If I'm understanding your question, before you perform any calculations you need to AND (&) your bytes against 255, so you'll be dealing with values from 0 to 255 instead of -128 to 127. When you assign a value higher than 127 to a byte it overflows, so 128 as a byte in java is -128, but after you AND (&) -128 against 255 you'll get +128.

// This prints 0 to 127, then -128 to -1
public static void main(String[] args) {
    for (int i = 0; i <= 255; i++) {
        System.out.println(((byte)i));
    }
}

// Where this will print 0 to 255
public static void main(String[] args) {
    for (int i = 0; i <= 255; i++) {
        System.out.println(((byte)i) & 255);
    }
}

Typically, in Java, this number would be represented as an int . That gives you more than enough room to store your values. If you need to represent it as a byte, for transmitting it somewhere or something like that, then you would cast it like

int i = 255;
byte b = (byte) (i & 0xff);

but in this case, it will still be negative, because byte is signed in Java.

Also, hexadecimal literals are by default of type int , as you've probably found out. So 0xff does have the value of 255 like you intend, but it's an int , not a byte .

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