• Post Reply Bookmark Topic Watch Topic
  • New Topic

Masking a byte  RSS feed

 
Parag Shah
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.math.BigInteger;

public class MathsExp {

public static void main(String[] args) {
byte b1 = (new BigInteger("2")).pow(8).intValue() - 1;
System.out.println("b1 " + b1);
System.out.println("Masked b1 with 0xFF " + (b1 & 0xFF));
System.out.println("Masked b1 with 0xFFFF " + (b1 & 0xFFFF));
}
}

Output:
b1 -1
Masked b1 with 0xFF 255
Masked b1 with 0xFFFF 65535


The first line of the output is expected: Since a byte is always signed 2^16 - 1 is taken as a negative number.

The second line is also understandable: since 0xFF is a short, the byte is propmoted to a short, hence ignoring the earlier sign bit. Performing an AND with 0xFF returns a short value of 255.

However I cannot understand why masking a byte with 0xFFFF returns 65535. The byte will be promoted to an int value and then AND will be performed with 0xFFFF. I would think this should return 255 as an int.

Am I missing something here?

Thanks
Parag
[ November 20, 2006: Message edited by: Parag Shah ]
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the byte is promoted to an int, its sign is extended. So the byte that contains 0xFF will be promoted to an int that contains 0xFFFFFFFF. Mask that with 0xFFFF and you get 0xFFFF (65535).
 
Parag Shah
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Jesper... that does solve the problem.

Regards
Parag
http://www.adaptivelearningonline.net
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!