C語言裏一般可能開發人員直接定義struct 做爲數據包,
所以在java客戶端接收struct 中的數據時候,受整數等類型的高低位存放的影響,
須要進行相應的轉換, html
參考: java
http://www.ibm.com/developerworks/cn/java/l-datanet/index.html 數組
轉換代碼以下: 工具
package com.lizongbo.util;
/**
*
* <p>Title: 數字轉換工具類</p>
*
* <p>Description: 將數字類型與byte數組互相轉換</p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: 618119.com</p>
*
* @author lizongbo
* @version 1.0
*/
public class NumberUtil {
/**
* 整數轉C++存放格式的字節數組
* @param v int
* @return byte[]
*/
public static byte[] int2Byte4C(int v) {
byte[] b = new byte[4];
//注意,不是java中的順序的 b[0],b[1],b[2],b[3]
b[3] = (byte) ( (v >>> 24) & 0xFF);
b[2] = (byte) ( (v >>> 16) & 0xFF);
b[1] = (byte) ( (v >>> 8) & 0xFF);
b[0] = (byte) ( (v >>> 0) & 0xFF);
return b;
} spa
/**
* C++存放格式的數組轉整數
* @param b byte[]
* @return int
*/
public static int byte2Int4C(byte[] b) {
return byte2Int(b, 0); .net
} htm
/**
* C++存放格式的數組轉整數
* @param b byte[]
* @param index int 指定的數組的起始索引位置
* @return int
*/
public static int byte2Int4C(byte[] b, int index) {
//注意,不是java中的順序的 b[0],b[1],b[2],b[3]
return (b[index + 3] & 0xff) << 24 |
(b[index + 2] & 0xff) << 16 |
(b[index + 1] & 0xff) << 8 |
b[index + 0] & 0xff; 索引
/**
下面這個是錯的 ,我被坑了 , 當時照抄 的 java.io.DataInputStream.readInt();
if ((ch1 | ch2 | ch3 | ch4) < 0) {
return 0;
}
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); ip
*/ 開發
}
/**
* 整數轉java存放格式的字節數組
* @param v int
* @return byte[]
*/
public static byte[] int2Byte(int v) {
byte[] b = new byte[4];
b[0] = (byte) ( (v >>> 24) & 0xFF);
b[1] = (byte) ( (v >>> 16) & 0xFF);
b[2] = (byte) ( (v >>> 8) & 0xFF);
b[3] = (byte) ( (v >>> 0) & 0xFF);
return b;
}
/**
* Java存放格式的數組轉整數
* @param b byte[]
* @return int
*/
public static int byte2Int(byte[] b) {
return byte2Int(b, 0);
}
/**
* Java存放格式的數組轉整數
* @param b byte[]
* @param index int 指定的數組的起始索引位置
* @return int
*/
public static int byte2Int(byte[] b, int index) {
return (b[index + 0] & 0xff) << 24 |
(b[index + 1] & 0xff) << 16 |
(b[index + 2] & 0xff) << 8 |
b[index + 3] & 0xff;
/**
下面這個是錯的 ,我被坑了 , 當時照抄 的 java.io.DataInputStream.readInt();
if ((ch1 | ch2 | ch3 | ch4) < 0) {
return 0;
}
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
*/
}
public static void main(String[] args) { for (int i = 40000; i < 40300; i++) { int r = byte2Int(int2Byte(i)); if (r != i) { System.out.println(i); } } } }