import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
Demo d = new Demo();
// 十六进制转十进制
byte[] result = d.getIntBit(x);
for(int i = 0; i < 32; i++)
System.out.print(result[i]);
System.out.println();
String s = d.toHex(result);
System.out.println(s);
System.out.println(d.toDec(s));
}
/**
* 将byte转换为一个长度为32的byte数组,数组每个值代表bit
*/
public byte[] getIntBit(int b) {
byte[] array = new byte[32];
for (int i = 31; i >= 0; i--) {
array[i] = (byte)(b & 1);
b = (byte) (b >> 1);
}
return array;
}
/**
* 转16进制
*/
public String toHex(byte[] b) {
String s = "";
//每四位处理一次
for(int i = 0; i < 32; i += 4) {
int temp = (b[i] * 8 + b[i+1] * 4 + b[i+2] * 2 + b[i+3]);
if(temp > 9) {
/*
switch(temp) {
case 10:s += 'A';break;
case 11:s += 'B';break;
case 12:s += 'C';break;
case 13:s += 'D';break;
case 14:s += 'E';break;
case 15:s += 'F';break;
}
*/
//=>A:65 -> 10 + 55 = 65
temp += 55;
s += (char)temp;
}else {
s += temp;
}
}
return s;
}
/**
* 转十进制
*/
public int toDec(String s) {
int result = 0;
for(int i = 0; i < 8; i++) {
int temp = s.charAt(i);
//9的ascii为57
if(temp > 57) {
temp -= 55; //'A'为65对应10,故减去55
}else {
temp -= 48;
}
result += temp * getProduct(7 - i);
}
return result;
}
/**
* 计算16的n次方
*/
public int getProduct(int n) {
int result = 1;
for(int i = 0; i < n; i++) {
result *= 16;
}
return result;
}
}
参考:java中bit的常用操作技巧 https://blog.csdn.net/wodeyuer125/article/details/45100319