int n= 0x234;

This will actually store 564 in n, but what if I want to have access and operate with 2,3 and 4?

有帮助吗?

解决方案

Hex digits are very easy to get: to access the value of the digit k, counting from right, shift the value right by 4*k, and mask with & 0x0F.

int n= 0x234;
int digit2 = (n >> 2*4) & 0x0F; // Gives you 2
int digit1 = (n >> 1*4) & 0x0F; // Gives you 3
int digit0 = (n >> 0*4) & 0x0F; // Gives you 4

其他提示

How about this:

ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(0x234);
for (byte b : bb.array()) {
    System.out.print(String.format("%02X ", b) + " "); //00 00 02 34
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top