[英]Decimal to Hexadecimal Converter in Java
I have a homework assignment where I need to do three-way conversion between decimal, binary and hexadecimal.我有一个家庭作业,我需要在十进制、二进制和十六进制之间进行三向转换。 The function I need help with is converting a decimal into a hexadecimal.我需要帮助的功能是将十进制转换为十六进制。 I have nearly no understanding of hexadecimal, nonetheless how to convert a decimal into hex.我几乎不了解十六进制,但如何将十进制转换为十六进制。 I need a function that takes in an int dec
and returns a String hex
.我需要一个接受int dec
并返回String hex
的函数。 Unfortunately I don't have any draft of this function, I'm completely lost.不幸的是,我没有这个功能的任何草稿,我完全迷失了。 All I have is this.我只有这个。
public static String decToHex(int dec)
{
String hex = "";
return hex;
}
Also I can't use those premade functions like Integer.toHexString() or anything, I need to actually make the algorithm or I wouldn't have learned anything.我也不能使用像 Integer.toHexString() 之类的预制函数或任何东西,我需要实际制作算法,否则我什么也学不到。
One possible solution:一种可能的解决方案:
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);
}
}
Output:输出:
1234BABE
Anyway, there is a library method for this:无论如何,有一个库方法:
String hex = Integer.toHexString(dec);
Simple:简单的:
public static String decToHex(int dec)
{
return Integer.toHexString(dec);
}
As mentioned here: Java Convert integer to hex integer如此处所述: Java Convert integer to hex integer
I need a function that takes in an int dec and returns a String hex.我需要一个接受 int dec 并返回 String hex 的函数。
I found a more elegant solution from http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html .我从http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html找到了一个更优雅的解决方案。 I changed a bit from the original ( see the edit )我从原来的改变了一点(见编辑)
// 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;
}
Disclaimer: I ask this question in my coding interview.免责声明:我在编码面试中问这个问题。 I hope this solution doesn't get too popular :)我希望这个解决方案不会太受欢迎:)
Edit June 17 2016 : I added the base
variable to give the flexibility to change into any base : binary, octal, base of 7 ... 2016 年 6 月 17 日编辑:我添加了base
变量以灵活地更改为任何 base :二进制、八进制、7 的基数......
According to the comments, this solution is the most elegant so I removed the implementation of Integer.toHexString()
.根据评论,这个解决方案是最优雅的,所以我删除了Integer.toHexString()
的实现。
Edit September 4 2015 : I found a more elegant solution http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html 2015 年 9 月 4 日编辑:我找到了一个更优雅的解决方案http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html
Consider dec2m method below for conversion from dec to hex, oct or bin.考虑下面的 dec2m 方法从 dec 到十六进制、八进制或二进制的转换。
Sample output is样本输出是
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;
}
}
Here is the code for any number :这是任何数字的代码:
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;
}
}
Another possible solution:另一种可能的解决方案:
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;
}
I will use我会用
Long a = Long.parseLong(cadenaFinal, 16 );
since there is some hex that can be larguer than intenger and it will throw an exception因为有一些十六进制可能比整数更大,它会抛出异常
Code to convert DECIMAL -to-> BINARY, OCTAL, HEXADECIMAL将 DECIMAL 转换为 -> BINARY、OCTAL、HEXADECIMAL 的代码
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));
}
}
Here's mine这是我的
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;
}
A better solution to convert Decimal To HexaDecimal and this one is less complex将 Decimal 转换为 HexaDecimal 的更好解决方案,这个解决方案不那么复杂
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);
}
}
Check out the code below for decimal to hexadecimal conversion,查看下面的十进制到十六进制转换的代码,
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();
}
}
You can learn more on different ways to convert decimal to hexadecimal in the following link >> java convert decimal to hexadecimal .您可以在以下链接中了解有关将十进制转换为十六进制的不同方法的更多信息 >> java convert decimal to hexadecimal 。
The following converts decimal to Hexa Decimal with Time Complexity : O(n) Linear Time with out any java inbuilt function以下将十进制转换为具有时间复杂度的十六进制:O(n) 线性时间,没有任何 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();
}
最简单的方法是:
String hexadecimalString = String.format("%x", integerValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.