问题
I'm looking for a method that converts binary numbers to hexa decimals (JAVA). Problem is that it can't be done with a predefined method and I just don't know how to do it. I've tried a few things but it throws me off that hexa decimals include chars.
thanks in advance!
回答1:
For your requirement first of all you have to convert binary no into decimal and then into hexadecimal. So please try this program it works as per your requirement :
import java.util.Scanner;
public class BinaryToHexa
{
public static void main(String args[])
{
int binnum, rem;
String hexdecnum="";
int decnum=0;
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Binary Number : ");
binnum = scan.nextInt();
// converting the number in decimal format
int i=0;
while(binnum>0)
{
rem = binnum%10;
binnum=binnum/10;
decnum = decnum + (int)(rem*Math.pow(2,i));
i++;
}
// converting the number in hexadecimal format
while(decnum>0)
{
rem = decnum%16;
hexdecnum = hex[rem] + hexdecnum;
decnum = decnum/16;
}
System.out.print("Equivalent Hexadecimal Value is :\n");
System.out.print(hexdecnum);
}
}
If you have any doubt please let me know.
Thanks...
回答2:
It's really a crappy question. You should explain what you have come up with and show the code you've tried so far.
So here's a binary number:
0101111010110010
Split it into groups of four bits (a bit is a binary digit, i.e. 1 or 0):
0101 1110 1011 0010
Now the funny thing is that each group of four bits has a maximum value of....
1111 = 8 + 4 + 2 + 1 = 15
Does that ring a bell? Here are the 'digits' in hexadecimal:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A, B, C, D, E, F
What's the maximum value of a single hexadecimal digit?
15
So this means you can simply translate each group of four bits into a hexadecimal digit:
0101 1110 1011 0010
4+1 8+4+2 8+2+1 2
5 14 11 2
5 E B 2
5EB2
回答3:
What is the exact issue or problem here?
Use Integer.toHexString(num) to convert
回答4:
Try this function from my library out. You do not do any calculation with this function. Only string compare, and you can convert as much binary to hexadecimal as you like. As long as the limitation on how long a string can be.
public static String binhexZ(String input)
{
String map = "0000,0,0001,1,0010,2,0011,3,0100,4,0101,5,0110,6,0111,7,1000,8,1001,9,1010,A,1011,B,1100,C,1101,D,1110,E,1111,F";
String output = "";
int i = 0;
while (input.length() % 4 != 0){
input = "0" + input;
}
while (i < input.length()){
output += map.charAt(map.indexOf(input.substring(i, i + 4)) + 5);
i = i + 4;
}
output = output.replaceAll("^0+", "");
output = output.length() < 1? "0" : output;
return output;
}
来源:https://stackoverflow.com/questions/41182257/binary-to-hexa-decimal-without-predefined-method-java