2012-03-09 109 views
1

任何人都可以解釋如何使用套接字編程從設備讀取數據。該設備正在發送Hexa格式,因此無法讀取該數據,請幫助我如何做到這一點。如何從設備讀取十六進制格式的數據?

StringBuffer instr = null; 
instr = new StringBuffer(); 
buf = new byte[4096]; 
int br = socket.getInputStream().read(buf); 
for(int i =0;i<br;i++){ 
      instr.append((char) buf[i]); 

      } 
data = instr.toString(); 

我使用上面的代碼,所以請幫助我。

+0

你的意思是你得到的二進制數據(即字節),不知道如何解釋這些數據呢?你知道這些數據的格式嗎? – Thomas 2012-03-09 09:42:46

+0

是得到二進制數據。該設備正在發送十六進制格式,但我們無法讀取其格式不可讀的格式。 – 2012-03-09 09:52:56

+0

解釋「Hexa」格式。給出一個「不可讀」輸入的例子。 – DwB 2012-03-09 09:58:05

回答

0

您可以嘗試此代碼段

public String convertHexToString(String hex){ 

      StringBuilder sb = new StringBuilder(); 
      StringBuilder temp = new StringBuilder(); 

      //49204c6f7665204a617661 split into two characters 49, 20, 4c... 
      for(int i=0; i<hex.length()-1; i+=2){ 

       //grab the hex in pairs 
       String output = hex.substring(i, (i + 2)); 
       //convert hex to decimal 
       int decimal = Integer.parseInt(output, 16); 
       //convert the decimal to character 
       sb.append((char)decimal); 

       temp.append(decimal); 
      } 
      System.out.println("Decimal : " + temp.toString()); 

      return sb.toString(); 
     } 
相關問題