I need to parse hex integer to decimal integer.
For example, Hex: 02 01 (513 in decimal mode) should represent 201. In code it could pass:
Assert.assertEquals(201, 开发者_Python百科parse(0x201));
How can I implement the method parse()? Thanks!
Use Integer.toHexString()
System.out.println(Integer.toHexString(0x201));
Output : 201
You can use the two-parameter version of parseInt:
Assert.assertEquals(513, Integer.parseInt("201", 16));
I think you just need to convert base 16 digits to base 10 digits, as follows:
int parse(int n) {
if (n == 0) return 0;
int digit = n & 0xf;
assert digit >= 0 && digit <= 9;
return parse(n >> 4) * 10 + digit;
}
probably won't work for negative numbers.
Why do you want to do this anyway? Seems a pretty silly thing to do.
I find String.format("%x", t)
works for the function. Anyway, thanks for Mark anirvan and Keith!
精彩评论