2013-07-12 67 views
-1

我有一個Java中的字節數組。這些值都是正值和負值(因爲它們在原始的無符號數組中大於127)。現在我想用Quickserver(http://www.quickserver.org/)將這個數組發送到我寫的iOS應用程序中的TCP客戶端。我將字節數組傳遞給sendClientBinary()方法,該方法接受字節數組作爲其輸入。但是,當我在iOS客戶端應用程序中接收數組時,所有負值似乎已被轉換爲某種補充形式,並且主要轉換爲兩字節值:Netbeans中的-71(0xB9)在Xcode內存視圖中查找爲0xC2 Netbeans中的0xB9和-67(0xBD)在Xcode中顯示爲0xC2 0xBD。 任何人都可以提供解釋嗎?從Java應用程序發送字節數組到iOS應用程序(使用快速服務器)

我也能夠將我的字節數組轉換爲char數組並掩蓋掉所有高位字節,所以現在char數組在正整數0-255範圍內保存了正確的值,但是,如何通過sendClientBinary()方法只接受字節數組作爲輸入的char數組。 我應該嘗試將char數組再次以某種方式轉換或轉換爲字節數組?

//Some code in Java: 
//reading my byte array from a method and converting it to char array (sorry if it's not the most efficient way, just need something simple right now 
byte byteArray[] = (byte[])functionReturningByteArray(); 
char charArray[] = new char[byteArray.length]; 
for (int ij = 0; ij < byteArray.length; ij++) 
{ 
    charArray[ij] = (char) byteArray[ij]; 
    if (charArray[ij] > 255) 
     charArray[ij] &= 0xFF; 
} 
//and the code sending the data over TCP socket (via Quickserver): 
clientH.setDataMode(DataMode.BINARY, DataType.OUT); 
clientH.sendClientBinary(byteArray); 
//--this is received in iOS as 16-bit values with some prefix such as 0xC2 or 0xC3 for negative values, if not for the prefix the value would be correct 


//or an attempt to send the charArray: 
clientH.setDataMode(DataMode.byte, DataType.OUT); 
clientH.sendClientBytes(charArray.toString()); 
//--this doesn't resemble my bytes once received in iOS at all 

//iOS reception code: 
case NSStreamEventHasBytesAvailable: 
{ 
    if(stream == inputStream) 
    { 
     int len = 0; 
     len = [inputStream read:receptionBuf maxLength:2048*2048*2]; 
     packetBytesReceived += len; 
     [packetData appendBytes:receptionBuf length:len]; 

     NSString* fullData = [[NSString alloc] initWithData:packetData encoding:NSASCIIStringEncoding]; 
... 
... 

我想問題可能是NSASCIIStringEncoding因爲我在我的數據包的主要部分接收字符,但有些內容只是字節的數據值,這或許可能是原因...?將開始工作。

+0

請張貼一些代碼。特別是接收端的代碼。 –

回答

0

0xc2是UTF-8編碼中字節的前綴。它表示您正在以0xc2序列發送UTF-8中的特殊字符。所以0xC2 0xB9會翻譯成上標字符;特別是^ 1。我的猜測(因爲我認爲這不是你實際發送的)是你的編碼設置不正確的地方。

+0

一些值的前綴爲0xC3,具體取決於正在傳輸的數字(我認爲從180開始的較大值有0xC3前綴),但是,在我的iOS應用程序中,我使用NSASCIIStringEncoding接收值,這可能是原因,而我去檢查。 – user2165039

+0

是從0xc1開始,這是正確的 –

0

問題解決。我直接從iOS應用程序中的packetData變量(而不是fullData即NSString)讀取數據有效負載的二進制部分,而不先將其轉換爲字符串,然後再次使用UTF8編碼解碼爲字節。

相關問題