简体   繁体   English

如何使用 Java 屏蔽十六进制 int?

[英]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 .在我的情况下,我不能使用像substring这样的 String 实用程序。

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.所以听起来你想要原始值的第 4-15 位,然后转移到结果的第 0-11 位。

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.两者都会为您提供(十进制)1596 =(十六进制)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.在这种特殊情况下,由于您的输入在位 12+ 中没有任何内容,因此不需要掩码 - 但如果您希望(例如)0x1263c5 的输入仍然为您提供与 0x63c 相对应的输出,则会出现这种情况。

If you want "63C" all you need is to shift right 4 bits (to drop the right most nibble ).如果你想要“63C”,你只需要右移 4 位(去掉最右边的半字节)。 Like,喜欢,

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

Outputs (as requested)输出(根据要求)

63c 63c

  int a = 0x63C5;
  int aftermask = a >> 4 ;     
  System.out.println( String.format("%X", aftermask) );

您需要使用的掩码是 0XFFF0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM