由于公司需要要重web开发 转入到 应用程序的开发。
 最近开始 搞 java的 串口通讯
  遇到 了 一个 问题
  我 现在 想 一个 字节数组到 comm1 端口
   那个  FEFEFE 16进制的 字节数组
   我 现在 这样 初始化 byte b[]  =  new byte(){Byte.praseByte("FE",16),Byte.praseByte("FE",16),Byte.praseByte("FE",16)}; 但是
 Byte.praseByte("FE",16)
这个 会说 超出了范围  
  我来我发现原来 byte 的范围 只有 -128-+127 Byte.praseByte("79",16)  中 的 79  已经 是 最大的范围了。我 一个 字节 要 发 “FE”  怎么 办 
我 刚想了 下  是不是用负数,是的话我 明天 就 去实践。
要是猜的不对的 话 请大家帮帮忙

解决方案 »

  1.   

    必须要字符串"FE"吗?byte b[]  =  new byte[]{ (byte)0xFE,(byte)0xFE,(byte)0xFE };不用在乎正负,用char也可以
      

  2.   

    难 到 这个 系列问题 没有人 回答吗?我 刚才  从串口 读出 信息 ,我 是用字节 byte[]读取的
    用 byte  是 
    -2  -2  -2  104  1  1  0  0  0  0  0  0
    怎么样 转成 16进制的 输出
    FE FE FE 68 01 01 00 00 00 00 00 00
      

  3.   

    刚好我也在做,呵呵,转么/**
       * byte转int
       * @param abyte0 byte[]
       * @return int
       */
      public static int Bytes4ToInt(byte abyte0[]) {
        return 0xff & abyte0[0] | (0xff & abyte0[1]) << 8 |
            (0xff & abyte0[2]) << 16 | (0xff & abyte0[3]) << 24;
      }  /**
       * int 转byte数组
       * @param x int
       * @return byte[]
       */
      public static byte[] IntToBytes4(int x) {
        byte[] b = new byte[4];
        b[0] = (byte) x;
        b[1] = (byte) (x >> 8);
        b[2] = (byte) (x >> 16);
        b[3] = (byte) (x >> 24);
        return b;
      }
      

  4.   

    直接调用Byte.toString(16)就可以了
      

  5.   


    public class Transfer { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    byte[] bt = new byte[]{-2,-2,-2 ,104 ,1 ,1 ,0 ,0 ,0 ,0 ,0 ,0};
    System.out.println(Transfer.Bytes2HexString(bt));
    }

    public static String Bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
          String hex = Integer.toHexString(b[i] & 0xFF);
          if (hex.length() == 1) {
            hex = '0' + hex;
          }
          ret += hex.toUpperCase();
        }
        return ret;
      }}
      

  6.   

    in to  bytepublic static byte [] int2bytes(int num){
    byte [] res = new byte[4];
    for (int i =0; i< 4; i++){
    res[i] = (byte)(num>>>(24-i*8));
    }
    return res;
    }byte to int
    public static int bytes2int(byte [] num){
    int res = 0;
    int mask = 0xff;
    for (int i =0; i<4; i++){
    res <<= 8;
    res |= (num[i]&mask);
    }
    return res;
    }