char c = 'a';
 byte[] buf = new byte[2];
 buf[0] = (byte) (c >> 8);
 buf[1] = (byte) c;
System.err.println((char)(((buf[0] & 0xff) << 8) | (buf[1] & 0xff)));
使用上述转化时,对于c是字符a时或者是97时,输出的结果都是字符a有什么办法可以使原来的字符是什么,输出的字符仍然是什么,
也就是说如果c是97 输出的结果就是97而不是a,
如果c是‘b’,输出的结果就是b

解决方案 »

  1.   

    你没处理符号,char是不带符号的public static byte[] charToByte(char ch){
        int temp=(int)ch;
        byte[] b=new byte[2];
        for (int i=b.length-1;i>-1;i--){
          b[i] = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位
          temp = temp >> 8;       //向右移8位
        }
        return b;
      }
      

  2.   

    System.err.println((char)(((buf[0] & 0xff) << 8) | (buf[1] & 0xff)));
    输出的是字符,因为你把它转为char了
    System.err.println((char)(((buf[0] & 0xff) << 8) | (buf[1] & 0xff)));
    你不把他转为char他不就输出的是数字了嘛
      

  3.   

    System.err.println((char)(((buf[0] & 0xff) << 8) | (buf[1] & 0xff)));输出的是字符,因为你把它转为char了
    System.err.println((((buf[0] & 0xff) << 8) | (buf[1] & 0xff)));
    你不把他转为char他不就输出的是数字了嘛