Java Hexa补充

时间:2011-07-04 14:34:05

标签: java hex

如何获得给定输入的互补十六进制值?

这可能有点通用,即有一个X可能值的数组,你如何转换像arr [x] - >的随机数组? arr [arr.length - arr.indexOf(x)]。

请忽略语法。

1 个答案:

答案 0 :(得分:1)

以下代码段将找到16个十六进制数的补码:

BigInteger subtrahend = new BigInteger("2D", 16); 
// input, you can take input from user and use after validation
char[] array = new char[subtrahend.toString(16).length()];
// construct a character array of the given length
Arrays.fill(array, 'F');
// fill the array by F, look at the first source there the FF is subtracted by 2D
BigInteger minuend = new BigInteger(new String(array), 16);
// construct FFF... Biginteger of that length
BigInteger difference = minuend.subtract(subtrahend);
// calculate minus
BigInteger result = difference.add(BigInteger.ONE);
// add one to it
System.out.println(result.toString(16));
// print it in hex format

希望这会对你有所帮助。谢谢。

来源:

  1. Binary and Hexadecimal Arithmetic
  2. Digital Principles and Logic Design

  3. 首先通过从数字FF中减去它来找到给定输入的15的补码,该数字与输入的长度相同。然后加1吧。