1、用Integer.toHexString方法即可将十进制装成十六进制。
package com.test;
public class Test {
public static void main(String[] args) {
int i = 123;
System.out.println(Integer.toHexString(i));
}
}
2、运行结果如下十进制的123转化成十六进制的7b
3、Integer.toHexString方法返回的结果是字符串。
4、直接表达16进制,在JAVA里面可以在数字前加"0x",像这样
int j = 0x7b;
System.out.println(Integer.decode("0x7b"));
import java.util.Scanner;
class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请出入一个十进制数");
int num = sc.nextInt();
toHex(num);
System.out.println(Integer.toHexString(num));// java自带的转换十六进制方法
sc.close();
}
public static void toHex(int num) {
if (num == 0) {
System.out.println('0');
return;
}
char[] chs = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F'};
char[] arr = new char[8];
int pos = arr.length;
while (num != 0) {
arr[--pos] = chs[num & 15];
num = num >>> 4;
}
for (int i = pos; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}
//两种方法:
import java.util.Scanner;
public class TentoSixteen{
private static StringBuilder sum = new StringBuilder();
private static int rulst; //定义一个结果,记录数与15的与运算结果,求得原数二进制最后四位的值
private static int count; //若数的二进制不止四位,定义一个数来记录除去后四位的新数,运用递归作用与rulst相同
private static void TtoSMethod1(int i) { //JDK自带的转化方法
String exchanged = Integer.toHexString(i);
System.out.println(exchanged);
}
private static void Sop() { //将得到的字符串反转
System.out.println(sum.reverse().toString());
}
private static void subim(int rulst) {//判断是否超出10,根据十六进制的规则超出10部分由字母ABCDEF代替
if(rulst<10) {
sum.append(rulst);
}else {
sum.append((char)('A'+(rulst-10)));//将int强制转换为char
}
}
private static void TtoSMethod2(int i) {
rulst =i&15;
if(i<(1<<4)&&i>=0) {//判断数有多少位,大于0小于16,则转换后打直接印
subim(rulst);
}else {//不止四位的数则用递归来多次运算
count=i>>4;//除去最后四位
subim(rulst);
TtoSMethod2(count);//递归直到count为0止
}
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("请出入一个十进制数:");
int num = scan.nextInt();
TtoSMethod1(num);//自带方法
TtoSMethod2(num);//自定义方法,可将任意的十进制转化为十六进制
Sop();//输出
}
}
package com;
import java.util.Scanner;
/**
*
* @author aming
*
*/
public class Aming {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入需要转换的数值:");
System.out.println(io(toHex(input.nextInt())));
}
static String io(String hi) {
if(hi.indexOf("-")>=0) {
hi = hi.replaceAll("-", "");
return "-"+hi;
}
return hi;
}
static String toHex(int hi) {
if(hi/16 == 0) {
return svn(hi);
}
return toHex(hi/16)+svn(hi);
}
static String svn(int To) {
switch (To%16) {
case 10: return "A";
case 11: return "B";
case 12: return "C";
case 13: return "D";
case 14: return "E";
case 15: return "F";
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 Integer.toString(To%16);
}
}
}