我正在尋找一種將二進制數轉換爲十六進制數(JAVA)的方法。問題在於它不能用預定義的方法完成,我只是不知道該怎麼做。我已經嘗試了一些東西,但它把我扔掉那個十六進制小數包括字符。二進制轉爲十六進制,不使用預定義的方法(JAVA)
在此先感謝!
我正在尋找一種將二進制數轉換爲十六進制數(JAVA)的方法。問題在於它不能用預定義的方法完成,我只是不知道該怎麼做。我已經嘗試了一些東西,但它把我扔掉那個十六進制小數包括字符。二進制轉爲十六進制,不使用預定義的方法(JAVA)
在此先感謝!
對於您的要求,首先你要二進制轉換沒有成十進制,然後轉換爲十六進制的。所以請嘗試這個程序它按照您的要求工作:
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);
}
}
如果您有任何疑問,請讓我知道。
謝謝...
是有可能從十六進制轉換爲二進制嗎? –
那一個使用預定義的方法parseint ... –
什麼是確切的問題或問題就在這裏?
使用Integer.toHexString(NUM)轉換
不能使用這樣的預定義的方法 –
這真是一個蹩腳的問題。你應該解釋你已經提出並展示你迄今爲止嘗試過的代碼。
所以這裏有一個二進制數:
0101111010110010
拆分成4位的組(一個位二進制數字,即0或1):
0101 1110 1011 0010
現在有趣的是每組四位有一個最大值....
1111 = 8 + 4 + 2 + 1 = 15
這是否響鈴?這裏是「數字」在hexadecimal:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A, B, C, D, E, F
什麼是一個十六進制數的最大值?
15
因此,這意味着你可以簡單地各四位組轉換爲十六進制數字:
0101 1110 1011 0010
4+1 8+4+2 8+2+1 2
5 14 11 2
5 E B 2
5EB2
嘗試從我的媒體庫了此功能。你不用這個函數做任何計算。只有字符串比較,並且可以根據需要將盡可能多的二進制轉換爲十六進制。只要限制一個字符串可以多長時間。
// "Copyright Notice", please do not remove.
// Written by Kevin Ng
// The full tutorial on this subject can be found @ http://kevinhng86.iblog.website or http://programming.world.edu.
// This source code file is a part of Kevin Ng's Z library.
// This source code is licensed under CCDL-1.0 A copy of CDDL1.0 can be found at https://opensource.org/licenses/CDDL-1.0
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;
}
我忘了提及我用輸入掃描器試過 –
我們不是在這裏做你的工作!我們在這裏幫助你解決確切的問題。所以告訴我們你的代碼並告訴我們什麼是不工作的。 –
歡迎來到Stackoverflow。請閱讀以下鏈接以改善您的問題:[Tour](http://stackoverflow.com/tour)| [如何問](http://stackoverflow.com/help/how-to-ask)| [最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。如前所述,顯示你的代碼和你的努力是非常重要的,所以人們可以基於它來幫助你,或者給你另一種方法。 – Tom