Reputation: 27375
I have an integer
int a = //...
int
s in java consist of 4 bytes. If we cast it to short
, we will take two least significant bytes. What is the fastest way to get short
consisting of 2 most significant byte
s of the int
?
short b = //take two most significant bytes of a
Upvotes: 1
Views: 619
Reputation: 18106
It is sufficient to use the right bit shift operator (>>
). Because the int
primitive data type has the size of 32 bits (Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)) and you need to get the 16 most significant bits, it is necessary to perform the right bit shift by 16 bits:
public class Program {
public static void main(final String[] args) {
final int input = 0xABCDEFAB;
final short output = (short) (input >> 16);
System.out.printf("Original integer: %X%n", input);
System.out.printf("Short with two most significant bytes: %X%n", output);
}
}
Also, it is worth noting that the Java language has signed (<<
, >>
) and unsigned (<<<
, >>>
) bit shift operators. Please refer to the article: Bitwise and Bit Shift Operators (The Java™ Tutorials > Learning the Java Language > Language Basics).
The same result can be produced using the division operator:
public class Program {
public static void main(final String[] args) {
final int input = 0xABCDEFAB;
final short output = (short) (input / 0x10000);
System.out.printf("Original integer: %X%n", input);
System.out.printf("Short with two most significant bytes: %X%n", output);
}
}
Upvotes: 4