5
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(input);
int a = Integer.parseInt(input.substring(2), 16);
System.out.println(Integer.toBinaryString(a));

Above mentioned code that takes in hex value and convert it into binary. However, this would not work on input "0xBE400000" but it works fine for "0x41C20000"

vindev
  • 2,240
  • 2
  • 13
  • 20
Yeram Hwang
  • 99
  • 1
  • 1
  • 10

3 Answers3

9

BE400000 is larger than Integer.MAX_VALUE (whose hex representation is 7FFFFFFF).

Therefore you'll need to parse it with

long a = Long.parseLong(input.substring(2), 16);
Eran
  • 387,369
  • 54
  • 702
  • 768
3

You can use Long

long l = Long.parseLong(input.substring(2), 16);

but if your value is greater than 2^63 - 1 you may use use a BigInteger's constructor:

BigInteger(String val, int radix) Translates the String representation of a BigInteger in the specified radix into a BigInteger.

BigInteger b = new BigInteger(input.substring(2), 16);

Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
Yoda
  • 17,363
  • 67
  • 204
  • 344
3

Since 0xBE400000 is in the range of an unsigned int you can use: parseUnsignedInt(String s, int radix)

int a = Integer.parseUnsignedInt(input.substring(2), 16);

With parseUnsignedInt(input, 16) you can parse values from 0x00000000 to 0xFFFFFFFF, where:

  • 0x00000000 = 0
  • 0x7FFFFFFF = 2147483647 (Integer.MAX_VALUE)
  • 0x80000000 = -2147483648 (Integer.MIN_VALUE)
  • 0xFFFFFFFF = -1
  • 0xBE400000 = -1103101952