开发者

Hex integer to decimal integer in Java

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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜