Jerrhann
Jerrhann

Reputation: 31

Java: How to get high and low 16bit values from a 32bit HEX?

Need a solution on how to perform the following: receive a decimal value, convert it to 32-bit Hex, then separate that 32-bit hex and get high 16-bit and low 16-bit values. I have been digging around net and cannot find much info.

Upvotes: 3

Views: 9266

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533590

Not sure why you are converting to hex but to turn a 32-bit value straight into two 16-bit values.

int x = ...
short high = x >> 16;
short low = x & 0xFFFF;

Upvotes: 6

kindall
kindall

Reputation: 184200

I expect this is a homework problem. Accordingly, I will give you information that can help you solve it rather than a solution.

  1. Convert the number to hexadecimal. This can be done with the Integer's toHexString() method.
  2. Add enough zeroes to the left to make it eight characters long (8 hexadecimal characters represent 32 bits). You can do this by adding zeroes one by one in a loop until it's 8 characters long, or (better approach) just add 7 zeroes to the left and only deal with the rightmost 8 characters.
  3. Take the the rightmost 4 characters as the lower 16 bits and the 4 characters immediately to the left of that as the higher 16 bits. This can be done with the String's substring() method along with length() and some simple subtraction.

Upvotes: 4

Related Questions