服务端是一个采集设备,现在用Java做客户端,现在发送指令过去(16进制的1200),需要转换成byte数组,用Java怎么实现啊?下面这些是VB的实现代码:
'发送指令函数
Private Function sendoutdata()
    Dim Buf$, i%
    Dim S3(1 To 1) As Byte
    Dim sj As String
    Dim sj_hex() As Byte
    Dim strsj As Byte
    If constate = 0 Then
        Exit Function
    End If
    If bHex1 = 0 Then
        Winsock1.SendData txtsend.Text '发送文本
    Else
        sj = Replace(txtsend, " ", "") '将空格去掉 '1200
        For i = 1 To Len(sj) 
        strsj = Asc(Mid(sj, i, 1))
        If (strsj >= 48 And strsj <= 57) Or (strsj >= 97 And strsj <= 102) Then        Else
            MsgBox "不是十六进制数据"
        Exit Function
        End If
        Next
        ReDim sj_hex(Len(sj) / 2 - 1)
        For i = 1 To Len(sj) Step 2
        sj_hex((i - 1) / 2) = Val("&H" & Mid(sj, i, 2)) '转换成十六进制
        Next
        Winsock1.SendData sj_hex
    End If
End Function

解决方案 »

  1.   


    static final char [] HEXs = new char[]{'0','1','2','3','4','5','6','7','8','9','};
    public byte [] convert(String hex){
    char [] chs = hex.toCharArray();
    if((chs.length&1)==1){
    throw new IllegalArgumentException("十六进制数字个数不正确,两个数字组成一个字节");
    }
    byte [] bs = new byte[(chs.length>>1)];
    for(int i=0;i<chs.length;i++){
    byte b = 0;
    if(chs[i]>='0' && chs[i]<='9'){
    b=(byte)(chs[i]-'0');
    }else if(chs[i]>='a' && chs[i]<='f'){
    b=(byte)(chs[i]-'a');
    }else if(chs[i]>='A' && chs[i]<='F'){
    b=(byte)(chs[i]-'A');
    }else{
    throw new IllegalArgumentException("第"+(i+1)+"个字符【"+chs[i]+"】不是十六进制数据");
    }
    if((i&1)==1){
    bs[i<<1] = (byte)(((bs[i<<1])<<4) & b);
    }else{
    bs[i<<1] = b;
    }
    }
    }
      

  2.   

    谢谢preferme。
    可是为嘛这句报数组越界的错误呢?
    bs[i<<1] = (byte)(((bs[i<<1])<<4) & b);
      

  3.   

    因为移位方向可能反了,
    两个十六进制字符,组成一个字节的数据。
    左移一位是数字的2倍,右移一位是数字的1/2.            if((i&1)==1){
                    bs[i>>1] = (byte)(((bs[i>>1])<<4) & b);
                }else{
                    bs[i>>1] = b;
                }