Java 将十六进制字符串转换为十进制整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20110533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:12:32  来源:igfitidea点击:

Converting Hexadecimal String to Decimal Integer

javahextype-conversion

提问by vontarro

I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b( something with letter) I got an error like this:

我写了一些代码将我的十六进制显示字符串转换为十进制整数。但是,当输入类似于 100a 或 625b(带有字母的东西)时,我收到了这样的错误:

java.lang.NumberFormatException: For input string: " 100a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)

java.lang.NumberFormatException:对于输入字符串:“100a”在 java.lang.NumberFormatException.forInputString(Unknown Source) 在 java.lang.Integer.parseInt(Unknown Source)

Do you have any idea how can I convert my string with letters to decimal integer?

您知道如何将带字母的字符串转换为十进制整数吗?

if(display.getText() != null)
{
    if(display.getText().contains("a") || display.getText().contains("b") || 
       display.getText().contains("c") || display.getText().contains("d") || 
       display.getText().contains("e") ||display.getText().contains("f"))
    {   
        temp1 = Integer.parseInt(display.getText(), 16);
        temp1 = (double) temp1;
    }
    else
    {
        temp1 = Double.parseDouble(String.valueOf(display.getText()));
    }
}

采纳答案by ajb

It looks like there's an extra space character in your string. You can use trim()to remove leading and trailing whitespaces:

您的字符串中似乎有一个额外的空格字符。您可以使用trim()删除前导和尾随空格:

temp1 = Integer.parseInt(display.getText().trim(), 16 );

Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.

或者,如果您认为空格的存在意味着还有其他问题,您必须自己查看,因为我们没有您的其余代码。

回答by TheOraclePhD

//package com.javatutorialhq.tutorial;

import java.util.Scanner;

/* * Java code convert hexadecimal to decimal */ 
public class HexToDecimal {

    public static void main(String[] args) {

        // TODO Auto-generated method stub 

        System.out.print("Hexadecimal Input:");

        // read the hexadecimal input from the console 

        Scanner s = new Scanner(System.in); 

        String inputHex = s.nextLine();

        try{ 

// actual conversion of hex to decimal

            Integer outputDecimal = Integer.parseInt(inputHex, 16);

            System.out.println("Decimal Equivalent : "+outputDecimal);


        }

        catch(NumberFormatException ne){

            // Printing a warning message if the input is not a valid hex number

            System.out.println("Invalid Input"); 

        }

        finally{ s.close();

        }
    } 
}

回答by Chandan

void htod(String hexadecimal)
{
    int h = hexadecimal.length() - 1;
    int d = 0;
    int n = 0;

    for(int i = 0; i<hexadecimal.length(); i++)
    {
        char ch = hexadecimal.charAt(i);
        boolean flag = false;
        switch(ch)
        {
            case '1': n = 1; break;
            case '2': n = 2; break;
            case '3': n = 3; break;
            case '4': n = 4; break;
            case '5': n = 5; break;
            case '6': n = 6; break;
            case '7': n = 7; break;
            case '8': n = 8; break;
            case '9': n = 9; break;
            case 'A': n = 10; break;
            case 'B': n = 11; break;
            case 'C': n = 12; break;
            case 'D': n = 13; break;
            case 'E': n = 14; break;
            case 'F': n = 15; break;
            default : flag = true;
        }
        if(flag)
        {
            System.out.println("Wrong Entry"); 
            break;
        }
        d = (int)(n*(Math.pow(16,h))) + (int)d;
        h--;
    }
    System.out.println("The decimal form of hexadecimal number "+hexadecimal+" is " + d);
}

回答by AlexAndro

  public static int hex2decimal(String s) {
             String digits = "0123456789ABCDEF";
             s = s.toUpperCase();
             int val = 0;
             for (int i = 0; i < s.length(); i++) {
                 char c = s.charAt(i);
                 int d = digits.indexOf(c);
                 val = 16*val + d;
             }
             return val;
         }

That's the most efficient and elegant solution I have found over the internet. Some of the others solutions provided here didn't always work for me.

这是我在互联网上找到的最有效和最优雅的解决方案。这里提供的其他一些解决方案并不总是对我有用。

回答by teteArg

This is my solution:

这是我的解决方案:

public static int hex2decimal(String s) {
    int val = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        int num = (int) c;
        val = 256*val + num;
    }
    return val;
}

For example to convert 3E8 to 1000:

例如将 3E8 转换为 1000:

StringBuffer sb = new StringBuffer();
sb.append((char) 0x03);
sb.append((char) 0xE8);
int n = hex2decimal(sb.toString());
System.out.println(n); //will print 1000.

回答by Nancy Gupta

public class Hex2Decimal {

公共类 Hex2Decimal {

public static void hexDec(String num)
{
    int sum=0;
    int newnum = 0;
    String digit = num.toUpperCase();
    for(int i=0;i<digit.length();i++)
    {
        char c = digit.charAt(digit.length()-i-1);

        if(c=='A')
        {
            newnum = 10;

        }
        else if(c=='B')
        {
            newnum = 11;

        }
        if(c=='C')
        {
            newnum = 12;

        }
        if(c=='D')
        {
            newnum = 13;

        }
        if(c=='E')
        {
            newnum = 14;

        }
        if(c=='F')
        {
            newnum = 15;

        }
        else
        {
            newnum = Character.getNumericValue(c);
        }
        sum = (int) (sum + newnum*Math.pow(16,i));


    }

    System.out.println(" HexaDecimal to Decimal conversion is" + sum);



}

public static void main(String[] args) {

公共静态无效主(字符串 [] args){

hexDec("9F");

} }

} }

回答by cri_sys

You can use this method to get the digit:

您可以使用此方法获取数字:

public int digitToValue(char c) {
   (c >= '&' && c <= '9') return c - '0';
   else if (c >= 'A' && c <= 'F') return 10 + c - 'A';
   else if (c >= 'a' && c <= 'f') return 10 + c - 'a';
   return -1;
 }

回答by Nguy?n Anh Giàu

My way:

我的方式:

private static int hexToDec(String hex) {
    return Integer.parseInt(hex, 16);
}

回答by Nguy?n Anh Giàu

Since there is no brute-force approach which (done with it manualy). To know what exactly happened.

由于没有蛮力方法(手动完成)。想知道究竟发生了什么。

Given a hexadecimal number

给定一个十六进制数

K?K???K???....K?K?K?

K?K???K???...K?K?K?

The equivalent decimal value is:

等效的十进制值为:

K? * 16? + K??? * 16??? + K??? * 16??? + .... + K? * 16? + K? * 16? + K? * 16?

克?* 16?+ K???* 16???+ K???* 16???+ .... + K?* 16?+ K?* 16?+ K?* 16?

For example, the hex number AB8Cis:

例如,十六进制数AB8C是:

10 * 16? + 11 * 16? + 8 * 16? + 12 * 16? = 43916

10 * 16?+ 11 * 16?+ 8 * 16?+ 12 * 16?= 43916

Implementation:

执行:

 //convert hex to decimal number
private static int hexToDecimal(String hex) {
    int decimalValue = 0;
    for (int i = 0; i < hex.length(); i++) {
        char hexChar = hex.charAt(i);
        decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
    }
    return decimalValue;
}
private static int hexCharToDecimal(char character) {
    if (character >= 'A' && character <= 'F')
        return 10 + character - 'A';
    else //character is '0', '1',....,'9'
        return character - '0';
}

回答by Shiva

Well, Mr.ajb has resolved and pointed out the error in your code.

嗯,ajb 先生已经解决并指出了您代码中的错误。

Coming to the second part of the code, that is, converting a string with letters to decimal integer below is code for that,

来到代码的第二部分,即将带有字母的字符串转换为下面的十进制整数是代码,

import java.util.Scanner;

public class HexaToDecimal
{
   int number;

   void getValue()
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter hexadecimal to convert: ");
      number = Integer.parseInt(sc.nextLine(), 16);
      sc.close();
   }

   void toConvert()
   {
      String decimal = Integer.toString(number);
      System.out.println("The Decimal value is : " + decimal);
   }

   public static void main(String[] args)
   {
      HexaToDecimal htd = new HexaToDecimal();
      htd.getValue();
      htd.toConvert();
   }
}

You can refer example on hexadecimal to decimalfor more information.

您可以参考十六进制到十进制的示例获取更多信息。