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"

1
  • 2
    ok. is this a statement, or is there a question coming? Commented Jan 23, 2018 at 8:53

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

and if Long isn't big enough, go to BigInteger/BigDecimal
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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.