簡體   English   中英

通過TCP將Java int發送到C

[英]Sending Java int to C over TCP

我正在嘗試通過TCP將Java的帶符號整數發送給C客戶端。

在Java端,我將整數寫入輸出流,如下所示:

static ByteBuffer wrapped = ByteBuffer.allocateDirect(4); // big-endian by default

public static void putInt(OutputStream out, int nr) throws IOException {
    wrapped.rewind();
    wrapped.putInt(nr);
    wrapped.rewind();

    for (int i = 0; i < 4; i++)
        out.write(wrapped.get());
}

在C端,我像這樣讀取整數:

int cnt = 0;
char buf[1];
char sizebuf[4];
while(cnt < 4) {
      iResult = recv(ConnectSocket, buf, 1, 0);
      if (iResult <= 0) continue;

      sizebuf[cnt] = buf[0];
      cnt++;
}

但是,如何在C中將char數組轉換為整數?

編輯

我已經嘗試了以下方法(以及相反的方法):

int charsToInt(char* array) {
     return (array[3] << 24) | (array[2] << 16) | (array[1] << 8) | array[0];   
}

再次編輯,因為我忘記了標簽。

數據

例如當前發生的情況:

我收到:

char 0
char 0
char 12
char -64
the int becomes 2448

並使用用於從char數組創建int的函數:

int charsToInt(char* array) {
    return ntohl(*((int*) array)); 
}

我希望有符號整數:3264

更新我將在睡覺后進行更多調查。

更新我有一個Java客戶端,它可以正確解釋整數並接收完全相同的字節:

0
0
12
-64

這取決於字節序,但是您想要:

 int x = sizebuf[0] + 
         (sizebuf[1] << 8) +
         (sizebuf[2] << 16) +
         (sizebuf[3] << 24);

要么:

 int x = sizebuf[3] + 
         (sizebuf[2] << 8) +
         (sizebuf[1] << 16) +
         (sizebuf[0] << 24);

請注意, sizebuf需要具有無符號類型才能正常工作。 否則,您需要屏蔽不需要的任何符號擴展值:

 int x = (sizebuf[3] & 0x000000ff) + 
         ((sizebuf[2] << 8) & 0x0000ff00) +
         ((sizebuf[1] << 16) & 0x00ff0000) +
         ((sizebuf[0] << 24) & 0xff000000);

經典的C庫具有您想要的方法,並且獨立於機器字節序: ntohl

// buf is a char */uint8_t *
uint32_t from_network = *((uint32_t *) buf);
uint32_t ret = ntohl(from_network);

與此相反, htonl則期望“網絡順序”為大端。

(上面的代碼假定buf至少有4個字節; ntohlhtonl的返回類型和參數類型為uint32_t ; JLS將int定義為4個字節,因此可以保證結果是)

要轉換char數組,一種可能是將其轉換為int *並存儲結果:

int result = *((int*) sizebuf)

這是有效的一行。 另一種可能性是根據字符計算整數。

for (i = 0 ; i < 4; i++) 
     result = result << sizeof(char) + buf[0]

選擇您喜歡的一種。

亞歷克西斯

編輯:sizeof(char)為1,因為sizeof返回字節結果。 所以右邊是:result = result <<(sizeof(char)* 8)+ buf [0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM