byte arythmetics

P

Philipp

Hello,

I can't understand how the following code works.
If I have a signed byte = -1 (1111 1111) and I logical-AND with 0xFF
(1111 1111) how come there is any effect?

Thanks Phil

--- SSCCE ---

public class byteTest {
public static void main(String[] args) {
byte a = -1;

System.out.println(a);
System.out.println((a & 0xFF));
// Output:
// -1
// 255
}
}
 
C

Chris Dollin

Philipp said:
I can't understand how the following code works.
If I have a signed byte = -1 (1111 1111) and I logical-AND with 0xFF
(1111 1111) how come there is any effect?

Thanks Phil

--- SSCCE ---

public class byteTest {
public static void main(String[] args) {
byte a = -1;

System.out.println(a);
System.out.println((a & 0xFF));
// Output:
// -1
// 255
}
}

There's no byte arithmetic: the operands are promoted to `int` if
necessary. So the 0xff value that's left is an int value -- 255.
 
P

Patricia Shanahan

Philipp said:
Hello,

I can't understand how the following code works.
If I have a signed byte = -1 (1111 1111) and I logical-AND with 0xFF
(1111 1111) how come there is any effect?

Thanks Phil

--- SSCCE ---

public class byteTest {
public static void main(String[] args) {
byte a = -1;

System.out.println(a);
System.out.println((a & 0xFF));
// Output:
// -1
// 255
}
}

a & 0xFF is an int expression, computed by converting a to int, then
doing the operation in 32 bit int arithmetic.

0xFF is int so it would be done that way even if Java supported byte
arithmetic. However, even if you add two byte expressions, it is done by
converting both to int and the result is int.

See the JLS, "5.6.2 Binary Numeric Promotion",
http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#170983

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,348
Latest member
RoscoeNevi

Latest Threads

Top