在JAVA中使用Socket和C#通讯的解决
由于JAVA使用的byte是有符号类型,而C#(包括C++)中的byte是无符号的,因此,在收发byte[]时都要进行转换处理,研究了几小时,发表解决方案如下:public class Test {/** * @param args */public static void main(String[] args) {//Send to C#byte[] a = Int2BytesLH(800);//模拟Recv from C#byte[] b = new byte[]{32,3,0,0};int c = Bytes2Int(BytestoHL(b));//Send to JAVAbyte[] a1 = Int2Bytes(800);//模拟Recv from JAVAbyte[] b1 = new byte[]{0,0,3,32};int c1 = Bytes2Int(b1);}/** * 将一个Int 数据,转换为byte数组. * JAVA直接使用 * @param intValue Int 数据 * @return byte数组. */ public static byte[] Int2Bytes(int intValue) { byte [] result = new byte; result = (byte) ((intValue & 0xFF000000) >> 24); result = (byte) ((intValue & 0x00FF0000) >> 16); result = (byte) ((intValue & 0x0000FF00) >> 8); result = (byte) ((intValue & 0x000000FF) ); return result; }/** * 将int转为低字节在前,高字节在后的byte数组 * 转为C#需要的的数组顺序 **/private static byte[] Int2BytesLH(int n) {byte[] b = new byte;b = (byte) (n & 0xff);b = (byte) (n >> 8 & 0xff);b = (byte) (n >> 16 & 0xff);b = (byte) (n >> 24 & 0xff);return b;}/** * 将byte[]转为低字节在前,高字节在后的byte数组 * 从C#收包后转换为JAVA的数组顺序 */private static byte[] BytestoHL(byte[] n) {byte[] b = new byte;b = n;b = n;b = n;b = n;return b;}/** * 将byte数组的数据,转换成Int值. * JAVA直接使用 * @param byteVal byte数组 * @return Int值. */ public static int Bytes2Int(byte[] byteVal) { int result = 0; for(int i = 0; i < byteVal.length; i ++) { int tmpVal = (byteVal << (8 * (3-i))); switch (i) { case 0: tmpVal = tmpVal & 0xFF000000; break; case 1: tmpVal = tmpVal & 0x00FF0000; break; case 2: tmpVal = tmpVal & 0x0000FF00; break; case 3: tmpVal = tmpVal & 0x000000FF; break; } result = result | tmpVal; } return result; }}
页:
[1]