Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mask a hexadecimal int using Java?

Tags:

java

hex

I have an integer that contains a hexa value. I want to extract the first characters from this hexa value like it was a String value but I don't want to convert it to a String.

int a = 0x63C5;
int afterMask= a & 0xFFF;
System.out.println(afterMask); // this gives me "3C5" but I want to get the value "63C" 

In my case I can't use String utilities like substring.

like image 618
e2rabi Avatar asked Nov 28 '22 22:11

e2rabi


2 Answers

It's important to understand that an integer is just a number. There's no difference between:

int x = 0x10;
int x = 16;

Both end up with integers with the same value. The first is written in the source code as hex but it's still representing the same value.

Now, when it comes to masking, it's simplest to think of it in terms of binary, given that the operation will be performed bit-wise. So it sounds like you want bits 4-15 of the original value, but then shifted to be bits 0-11 of the result.

That's most simply expressed as a mask and then a shift:

int afterMask = (a & 0xFFF0) >> 4;

Or a shift then a mask:

int afterMask = (a >> 4) & 0xFFF;

Both will give you a value of (decimal) 1596 = (hex) 63C.

In this particular case, as your input didn't have anything in bits 12+, the mask is unnecessary - but it would be if you wanted an input of (say) 0x1263c5 to still give you an output corresponding to 0x63c.

like image 159
Jon Skeet Avatar answered Dec 04 '22 14:12

Jon Skeet


If you want "63C" all you need is to shift right 4 bits (to drop the right most nibble). Like,

int a = 0x63C5;
int afterMask = a >> 4;
System.out.println(Integer.toHexString(afterMask));

Outputs (as requested)

63c

like image 38
Elliott Frisch Avatar answered Dec 04 '22 14:12

Elliott Frisch