Convertisseur Décimal en Hexadécimal en Java


J'ai un devoir où je dois faire une conversion à trois voies entre décimal, binaire et hexadécimal. La fonction avec laquelle j'ai besoin d'aide convertit une décimale en hexadécimal. Je n'ai presque aucune compréhension de l'hexadécimal, néanmoins comment convertir une décimale en hexadécimal. J'ai besoin d'une fonction qui prend un int dec et retourne un String hex. Malheureusement, je n'ai aucun brouillon de cette fonction, je suis complètement perdu. Tout ce que j'ai est ce.

  public static String decToHex(int dec)
  {
    String hex = "";


    return hex;
  }

Je ne peux pas non plus utiliser ces prémâchés fonctions comme Entier.toHexString () ou quoi que ce soit, j'ai besoin de faire l'algorithme ou je n'aurais rien appris.

Author: Bart, 2012-11-20

12 answers

Une solution possible:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Sortie:

1234BABE

Quoi qu'il en soit, il existe une méthode de bibliothèque pour cela:

String hex = Integer.toHexString(dec);
 33
Author: kol, 2012-11-20 01:35:17

Simple:

  public static String decToHex(int dec)
  {
        return Integer.toHexString(dec);
  }

Comme indiqué ici: Java Convertir entier de hex integer

 13
Author: Andreas L., 2017-05-23 12:17:49

J'ai besoin d'une fonction qui prend un int dec et renvoie une chaîne hex.

J'ai trouvé une solution plus élégante de http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html . J'ai changé un peu de l'original (voir l'édition)

// precondition:  d is a nonnegative integer
public static String decimal2hex(int d) {
    String digits = "0123456789ABCDEF";
    if (d <= 0) return "0";
    int base = 16;   // flexible to change in any base under 16
    String hex = "";
    while (d > 0) {
        int digit = d % base;              // rightmost digit
        hex = digits.charAt(digit) + hex;  // string concatenation
        d = d / base;
    }
    return hex;
}

Avertissement: J'utilise cet algorithme dans mon entretien de codage. J'espère que cette solution ne deviendra pas trop populaire:)

Edit du 17 juin 2016 : j'ai ajouté le base variable pour donner la flexibilité de changer dans n'importe quelle base : binaire, octal, base de 7 ...
Selon les commentaires, cette solution est la plus élégante, j'ai donc supprimé l'implémentation de Integer.toHexString().

Edit du 4 septembre 2015 : j'ai trouvé une solution plus élégante http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html

 11
Author: Raymond Chenon, 2016-06-17 15:31:13

Considérez la méthode dec2m ci-dessous pour la conversion de dec en hex, oct ou bin.

La sortie de l'échantillon est

28 dec == 11100 bin 28 dec == 34 oct 28 dec == 1C hex

public class Conversion {
    public static void main(String[] argv) {
        int x = 28;                           // sample number
        if (argv.length > 0)
            x = Integer.parseInt(argv[0]);    // number from command line

        System.out.printf("%d dec == %s bin\n", i, dec2m(x, 2));
        System.out.printf("%d dec == %s oct\n", i, dec2m(x, 8));
        System.out.printf("%d dec == %s hex\n", i, dec2m(x, 16));
    }

    static String dec2m(int N, int m) {
        String s = "";
        for (int n = N; n > 0; n /= m) {
            int r = n % m;
            s = r < 10 ? r + s : (char) ('A' - 10 + r) + s;
        }
        return s;
    }
}
 2
Author: Andrej, 2014-10-31 01:18:28

Une autre solution possible:

public String DecToHex(int dec){
  char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'A', 'B', 'C', 'D', 'E', 'F'};
  String hex = "";
  while (dec != 0) {
      int rem = dec % 16;
      hex = hexDigits[rem] + hex;
      dec = dec / 16;
  }
  return hex;
}
 1
Author: prometeus10, 2016-03-27 11:35:57

Voici le code pour n'importe quel nombre :

import java.math.BigInteger;

public class Testing {

/**
 * @param args
 */
static String arr[] ={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; 
public static void main(String[] args) {
    String value = "214";
    System.out.println(value + " : " + getHex(value));
}


public static String getHex(String value) {
    String output= "";
    try {
        Integer.parseInt(value);
        Integer number = new Integer(value);
        while(number >= 16){
            output = arr[number%16] + output;
            number = number/16;
        }
        output = arr[number]+output;

    } catch (Exception e) {
        BigInteger number = null;
        try{
            number = new BigInteger(value);
        }catch (Exception e1) {
            return "Not a valid numebr";
        }
        BigInteger hex = new BigInteger("16");
        BigInteger[] val = {};

        while(number.compareTo(hex) == 1 || number.compareTo(hex) == 0){
            val = number.divideAndRemainder(hex);
            output = arr[val[1].intValue()] + output;
            number = val[0];
        }
        output = arr[number.intValue()] + output;
    }

    return output;
}

}
 0
Author: Ankit Singla, 2013-12-05 07:11:23

Je vais utiliser

Long a = Long.parseLong(cadenaFinal, 16 );

Puisqu'il y a un hexadécimal qui peut être plus large qu'intenger et il lancera une exception

 0
Author: D4rWiNS, 2015-02-11 10:01:20

Voici le mien

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}
 0
Author: Idan, 2016-05-28 16:15:47

Une meilleure solution pour convertir Décimal en HexaDécimal et celui-ci est moins complexe

import java.util.Scanner;
public class DecimalToHexa
{
    public static void main(String ar[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a Decimal number: ");
        int n=sc.nextInt();
        if(n<0)
        {
            System.out.println("Enter a positive integer");
            return;
        }
        int i=0,d=0;
        String hx="",h="";
        while(n>0)
        {
            d=n%16;`enter code here`
            n/=16;
            if(d==10)h="A";
            else if(d==11)h="B";
            else if(d==12)h="C";
            else if(d==13)h="D";
            else if(d==14)h="E";
            else if(d==15)h="F";
            else h=""+d;            
            hx=""+h+hx;
        }
        System.out.println("Equivalent HEXA: "+hx);
    }
}        
 0
Author: user8720114, 2017-10-04 12:43:30

Consultez le code ci-dessous pour la conversion décimale en hexadécimal,

import java.util.Scanner;

public class DecimalToHexadecimal
{
   public static void main(String[] args)
   {
      int temp, decimalNumber;
      String hexaDecimal = "";
      char hexa[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter decimal number : ");
      decimalNumber = sc.nextInt();

      while(decimalNumber > 0)
      {
         temp = decimalNumber % 16;
         hexaDecimal = hexa[temp] + hexaDecimal;
         decimalNumber = decimalNumber / 16;
      }

      System.out.print("The hexadecimal value of " + decimalNumber + " is : " + hexaDecimal);      
      sc.close();
   }
}

Vous pouvez en savoir plus sur les différentes façons de convertir décimal en hexadécimal dans le lien suivant >> java convertir décimal en hexadécimal.

 0
Author: Shiva, 2017-11-21 10:30:07

Ce qui suit convertit décimal en Hexa Décimal avec Complexité temporelle: O (n) Temps linéaire sans aucune fonction intégrée java

private static String decimalToHexaDecimal(int N) {
    char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuilder builder = new StringBuilder();
    int base= 16;
    while (N != 0) {
        int reminder = N % base;
        builder.append(hexaDecimals[reminder]);
        N = N / base;
    }

    return builder.reverse().toString();
}
 0
Author: Sameer Shrestha, 2018-05-17 17:33:03

Code pour convertir DÉCIMAL-en - > BINAIRE, OCTAL, HEXADÉCIMAL

public class ConvertBase10ToBaseX {
    enum Base {
        /**
         * Integer is represented in 32 bit in 32/64 bit machine.
         * There we can split this integer no of bits into multiples of 1,2,4,8,16 bits
         */
        BASE2(1,1,32), BASE4(3,2,16), BASE8(7,3,11)/* OCTAL*/, /*BASE10(3,2),*/ 
        BASE16(15, 4, 8){       
            public String getFormattedValue(int val){
                switch(val) {
                case 10:
                    return "A";
                case 11:
                    return "B";
                case 12:
                    return "C";
                case 13:
                    return "D";
                case 14:
                    return "E";
                case 15:
                    return "F";
                default:
                    return "" + val;
                }

            }
        }, /*BASE32(31,5,1),*/ BASE256(255, 8, 4), /*BASE512(511,9),*/ Base65536(65535, 16, 2);

        private int LEVEL_0_MASK;
        private int LEVEL_1_ROTATION;
        private int MAX_ROTATION;

        Base(int levelZeroMask, int levelOneRotation, int maxPossibleRotation) {
            this.LEVEL_0_MASK = levelZeroMask;
            this.LEVEL_1_ROTATION = levelOneRotation;
            this.MAX_ROTATION = maxPossibleRotation;
        }

        int getLevelZeroMask(){
            return LEVEL_0_MASK;
        }
        int getLevelOneRotation(){
            return LEVEL_1_ROTATION;
        }
        int getMaxRotation(){
            return MAX_ROTATION;
        }
        String getFormattedValue(int val){
            return "" + val;
        }
    }

    public void getBaseXValueOn(Base base, int on) {
        forwardPrint(base, on);
    }

    private void forwardPrint(Base base, int on) {

        int rotation = base.getLevelOneRotation();
        int mask = base.getLevelZeroMask();
        int maxRotation = base.getMaxRotation();
        boolean valueFound = false;

        for(int level = maxRotation; level >= 2; level--) {
            int rotation1 = (level-1) * rotation;
            int mask1 = mask << rotation1 ;
            if((on & mask1) > 0 ) {
                valueFound = true;
            }
            if(valueFound)
            System.out.print(base.getFormattedValue((on & mask1) >>> rotation1));
        }
        System.out.println(base.getFormattedValue((on & mask)));
    }

    public int getBaseXValueOnAtLevel(Base base, int on, int level) {
        if(level > base.getMaxRotation() || level < 1) {
            return 0; //INVALID Input
        }
        int rotation = base.getLevelOneRotation();
        int mask = base.getLevelZeroMask();

        if(level > 1) {
            rotation = (level-1) * rotation;
            mask = mask << rotation;
        } else {
            rotation = 0;
        }


        return (on & mask) >>> rotation;
    }

    public static void main(String[] args) {
        ConvertBase10ToBaseX obj = new ConvertBase10ToBaseX();

        obj.getBaseXValueOn(Base.BASE16,12456); 
//      obj.getBaseXValueOn(Base.BASE16,300); 
//      obj.getBaseXValueOn(Base.BASE16,7); 
//      obj.getBaseXValueOn(Base.BASE16,7);

        obj.getBaseXValueOn(Base.BASE2,12456);
        obj.getBaseXValueOn(Base.BASE8,12456);
        obj.getBaseXValueOn(Base.BASE2,8);
        obj.getBaseXValueOn(Base.BASE2,9);
        obj.getBaseXValueOn(Base.BASE2,10);
        obj.getBaseXValueOn(Base.BASE2,11);
        obj.getBaseXValueOn(Base.BASE2,12);
        obj.getBaseXValueOn(Base.BASE2,13);
        obj.getBaseXValueOn(Base.BASE2,14);
        obj.getBaseXValueOn(Base.BASE2,15);
        obj.getBaseXValueOn(Base.BASE2,16);
        obj.getBaseXValueOn(Base.BASE2,17);


        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 3)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 4)); 

        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,15, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,30, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 2)); 

        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 1)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 1));
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 2)); 
        System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 513, 2)); 


    }
}
 -1
Author: Kanagavelu Sugumar, 2015-08-31 08:44:07