Java 實現控制檯輸入任意字符,轉換成十六進制、二進制和十進制

import java.io.*;

public class StringtoNum {
/*
* 16進制數字字符集
*/
private static String hexString = "0123456789ABCDEF";

/*
* 將字符串編碼成16進制數字,適用於所有字符(包括中文)
*/
public static String encode(String str) {
// 根據默認編碼獲取字節數組
byte[] bytes = str.getBytes();
StringBuilder sb = new StringBuilder(bytes.length * 2);
// 將字節數組中每個字節拆解成2位16進制整數
for (int i = 0; i < bytes.length; i++) {
sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
}
return sb.toString();
}

/*
* 將16進制數字解碼成字符串,適用於所有字符(包括中文)
*/
public static String decode(String bytes) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(
bytes.length() / 2);
// 將每2位16進制整數組裝成一個字節
for (int i = 0; i < bytes.length(); i += 2)
baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
.indexOf(bytes.charAt(i + 1))));
return new String(baos.toByteArray());
}

/**
*
* @param hexString
* @return 將十六進制轉換爲字節數組
*/
public static byte[] HexStringToBinary(String hexStr){
//hexString的長度對2取整,作爲bytes的長度
int len = hexStr.length()/2;
byte[] bytes = new byte[len];
byte high = 0;//字節高四位
byte low = 0;//字節低四位

for(int i=0;i<len;i++){
//右移四位得到高位
high = (byte)((hexString.indexOf(hexStr.charAt(2*i)))<<4);
low = (byte)hexString.indexOf(hexStr.charAt(2*i+1));
bytes[i] = (byte) (high|low);//高地位做或運算
}
return bytes;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
try {
System.out.println("Enter the string: ");
str = br.readLine();
System.out.println("Convert the string to hexString: ");
System.out.println(StringtoNum.encode(str));
System.out.println("Convert the hexString to binaryString: ");
System.out.println(Integer.toBinaryString(Integer.parseInt(StringtoNum.encode(str), 16)));
System.out.println("Convert the hexString to int: ");
System.out.println(Integer.parseInt(StringtoNum.encode(str), 16));
System.out.println("Convert the hexString to string: ");
System.out.println(StringtoNum.decode(StringtoNum.encode(str)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章