2016年8月24日 星期三

[ Java 常見問題 ] Convert hex string to binary string

Source From Here
Question
I would like to convert a hex string to a binary string. For example, Hex 2 is 0010. Below is the code:
  1. String HexToBinary(String Hex)  
  2. {  
  3.     int i = Integer.parseInt(Hex);  
  4.     String Bin = Integer.toBinaryString(i);  
  5.     return Bin;  
  6. }  
However this only works for Hex 0 - 9; it won't work for Hex A - F because it uses int. Can anyone enhance it?

How-To
You need to tell Java that the int is in hex, like this:
  1. String hexToBinary(String hex) {  
  2.     int i = Integer.parseInt(hex, 16);  
  3.     String bin = Integer.toBinaryString(i);  
  4.     return bin;  
  5. }  
Another approach is to used exist library. For example, flib:
  1. package test;  
  2.   
  3. import flib.util.HexByteKit;  
  4.   
  5. public class Test {  
  6.   
  7.     public static void main(String[] args) {  
  8.         String hexStrs[] = { "12F""3E" };       
  9.         try {  
  10.             for (int i = 0; i < hexStrs.length; i++) {  
  11.   
  12.                 String hxs = hexStrs[i];  
  13.                 String obs = HexByteKit.Hex2Bin(hxs);  
  14.                 System.out.printf("%s(%d)=%s\n", hxs,  
  15.                         Integer.parseInt(hxs, 16), obs);  
  16.             }  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21. }  
Execution result:
12F(303)=000100101111
3E(62)=00111110


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...