Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert all hex values to binary

Tags:

java

integer

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"

like image 371
Yeram Hwang Avatar asked Jan 23 '18 08:01

Yeram Hwang


People also ask

Can hex convert to binary directly?

Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.

Why do we convert binary to hexadecimal?

The choice of hexadecimal representation is taken because of human readability and ease of conversion. This also works the other way round so its much easier for big binary numbers (that appear in memory addresses) to convert them into hex and manipulate them with this representations.


1 Answers

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);
like image 58
Eran Avatar answered Oct 21 '22 13:10

Eran