Skip to content

How can I mask a hexadecimal int using Java?

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.



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.

User contributions licensed under: CC BY-SA
1 People found this is helpful