java socket 如何发送16进制数据

解决方案 »

  1.   

    发送消息之前转码为16进制 public static final String encodeHex(String msg) {
    byte[] bytes = null;
    try {
    bytes = msg.getBytes("GBK");
    } catch (java.io.UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    StringBuffer buff = new StringBuffer(bytes.length * 4);
    String b;
    char a;
    int n = 0;
    int m = 0;
    for (int i = 0; i < bytes.length; i++) {
    b = Integer.toHexString(bytes[i]);
    if (bytes[i] > 0) {
    buff.append("00");
    buff.append(b);
    n = n + 1;
    } else {
    a = msg.charAt((i - n) / 2 + n);
    m = a;
    b = Integer.toHexString(m);
    buff.append(b.substring(0, 4)); i = i + 1;
    }
    }
    return buff.toString();
    }
      

  2.   

    public static final String encodeHex(String msg) {
    byte[] bytes = null;
    try {
    bytes = msg.getBytes("GBK");
    } catch (java.io.UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    StringBuffer buff = new StringBuffer(bytes.length * 4);
    String b;
    char a;
    int n = 0;
    int m = 0;
    for (int i = 0; i < bytes.length; i++) {
    b = Integer.toHexString(bytes[i]);
    if (bytes[i] > 0) {
    buff.append("00");
    buff.append(b);
    n = n + 1;
    } else {
    a = msg.charAt((i - n) / 2 + n);
    m = a;
    b = Integer.toHexString(m);
    buff.append(b.substring(0, 4)); i = i + 1;
    }
    }
    return buff.toString();
    }