二进制字符串为十六进制的Java [英] String binary to Hex Java

查看:137
本文介绍了二进制字符串为十六进制的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code,看起来像这样

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


}

第一个字符串转换得很好,但第二个具有java.lang.NumberFormatException的错误
不知道是什么问题。

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

推荐答案

在32个字符的二进制数的最显著位设置为 1 ,结果值超出 INT 支持的正数的范围,再也不能PTED为有效整数间$ p $。这将导致根据文档除外:

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:

NumberFormatException类型的异常如果发生下列情况时抛出:

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


      
  • 第一个参数是null或零长度的字符串。

  •   
  • 的基数可以是小于Character.MIN_RADIX,或大于Character.MAX_RADIX。

  •   
  • 字符串的任何字符不是指定基数的数字,除非第一个字符是减号' - '('\\ u002D')为提供的字符串比长1长

  •   
  • 由字符串psented转口货值为$ P $不是int类型的值。(重点是我的)

  •   
  • 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 '-' ('\u002D') 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)

为了进入这个负二进制值,使用 - 在您的号码前符号,其余位转换成2的补再presentation。

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.

如果您需要长度超过32位,或者如果您想值继续成为PTED为正数间$ P $,你需要切换到64位整数数据类型的数字。

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.

这篇关于二进制字符串为十六进制的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆