2016-07-14 56 views
0

我需要將十六進制數字表示爲字符串轉換爲帶符號的8位字符串。Java將十六進制轉換爲帶符號的8位代碼

例如:鑑於此代碼段:

String hexideciaml = new String("50 4b e0 e7"); 
String signed8Bit = convertHexToSigned8Bit(hexideciaml); 
System.out.print(signed8Bit); 

輸出應該是: 「80 75 -32 -25」

所以我非常希望實現的一部分這個網站在Java中。 https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

更新:解決方案需要JRE6沒有其他Jars。

+2

爲什麼會在 「50」 仍然unhexified?我希望輸出爲「80 75 -32 -25」 – Roshan

+1

使用空格作爲分隔符解析'String'。然後通過'Integer.parseInt(String,int)'將每個值轉換爲一個基數爲16的Integer。將該值轉換爲'byte'將其轉換爲有符號值。 –

+0

你是對的@Reimeus。更新問題。對於那個很抱歉。 – javaPlease42

回答

3

的Java 1.8(流)

import java.util.Arrays; 

public class HexToDec { 

    public static String convertHexToSigned8Bit(String hex) { 
     return Arrays 
       .stream(hex.split(" +")) 
       .map(s -> "" + (byte) Integer.parseInt(s, 16)) 
       .reduce((s, s2) -> s + " " + s2) 
       .get(); 
    } 


    public static void main(String[] args) { 
     String hexidecimal = "50 4b e0 e7"; 
     String signed8Bit = convertHexToSigned8Bit(hexidecimal); 
     System.out.print(signed8Bit); 
    } 

} 

的Java < 1.8

import java.util.Arrays; 

public class HexToDec { 

    public static String convertHexToSigned8Bit(String hex) { 
     String[] tokens = hex.split(" +"); 
     StringBuilder result = new StringBuilder(); 
     for (int i = 0; i < tokens.length - 1; i++) { //append all except last 
      result.append((byte) Integer.parseInt(tokens[i], 16)).append(" "); 
     } 
     if (tokens.length > 1) //if more than 1 item in array, add last one 
      result.append((byte) Integer.parseInt(tokens[tokens.length - 1], 16)); 
     return result.toString(); 
    } 


    public static void main(String[] args) { 
     String hexidecimal = "50 4b e0 e7"; 
     String signed8Bit = convertHexToSigned8Bit(hexidecimal); 
     System.out.print(signed8Bit); 
    } 

} 

輸出爲:80 75 -32 -25

+0

嗯似乎並沒有編譯。我得到這個錯誤'方法流(String [])未定義類型數組',解決方案需要爲JRE6。還有's2'在哪裏初始化? – javaPlease42

+1

Ofc它不會爲JRE6編譯。我使用了JRE8以來的流。等一下,我會重寫它爲JRE6 –

+0

正是@Vladislav Gutov。我很感激,謝謝。 – javaPlease42

相關問題