简体   繁体   中英

String binary to Hex Java

i have code that looks like this

             public static void main(String[] args) {
    String string= "11011100010000010001000000000000";
   String string1= "00000000010000110000100000101100";

    System.out.println(Integer.toHexString(Integer.parseInt(string1,2)));

    System.out.println(Integer.toHexString(Integer.parseInt(string,2)));


}

the first string convert just fine but the second one has an error of java.lang.NumberFormatException dont know what the problem is

try this:

Long.toHexString(Long.parseLong(string,2))

(edited from parsLong to parseLong)

For what's worth, you can also use the BigInteger class :

String string  = "11011100010000010001000000000000";
String string1 = "00000000010000110000100000101100";

System.out.println(new BigInteger(string1, 2).toString(16));
System.out.println(new BigInteger(string, 2).toString(16));

您可以使用Long而不是IntegerLong.parseLongLong.toHexString方法)。

When the most significant bit of a 32-character binary number is set to 1 , the resultant value exceeds the range of positive numbers supported by int , and can no longer be interpreted as a valid integer number. This causes the exception according to the documentation:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\-') provided that the string is longer than length 1.
  • The value represented by the string is not a value of type int. (emphasis is mine)

In order to enter this negative binary value, use - sign in front of your number, and convert the remaining bits to 2-s complement representation.

If you need numbers that are longer than 32 bits, or if you would like the value to continue being interpreted as a positive number, you would need to switch to the 64-bit integer data type.

If you want to parse to integer, the range should be

10000000000000000000000000000000 to 01111111111111111111111111111111

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM