2012-07-05 18 views
1

解析器有問題。Java - Parser Library解析x位中的小數到字節

問題是我得到一個整數,如「8」,我需要將其轉換爲一個8位無符號字節。 稍後我會收到一個整數「56」,需要使用相同的方法進行轉換,但是當我得到一個「-53」(例如)時,我會說這是通信和發送中的錯誤。

例如,

number = 538; //or 63492873 or 8 or 17826312631 or -231 or whatever 
try{ 
    byte response[] = Parse8BitUnsigned(number); 
}catch(Idkexcepcion ex){ 
    System.out.println("the number is a signed one"); 
    byte response[] = Parse8BitSigned(number); 
} 

注:Parse8BitSigned()和Parse8BitSigned()沒有得到執行。我需要一個方法爲任意數量的

+3

什麼是你的問題,是'java.lang.Integer.valueOf(「8」)'答案嗎? – 2012-07-05 20:40:45

+0

我的問題是,詮釋8位數組在字節,如 字節響應[] = Parse8Bit(8); – GunBlade 2012-07-05 20:42:18

+0

你想要的只是解析**正的**值,而不是'unsigned'。 'unsigned'和'signed'是一個表示。例如有符號的字節範圍從[-128; 127] – 2012-07-05 21:14:55

回答

0

您可以使用ByteBuffer做你想要什麼:

String number="8"; 
int num = Integer.valueOf(number); 
if(num < 0) //ERROR 
// Return 8 in a 4 bytes array 
byte[] bytes = ByteBuffer.allocate(4).putInt(num).array();