功能:把一个中文的char转换成byte,然后又从byte中,能恢复出这个char
说明:由于其它原因,必须用位移。就这个烦。
public void convert()
{
     byte bt[] = new byte[4];
 long lc= 29579; //"这个字是“王”的char "
 char c = (char)lc;
               
               /* 这个地方没对,唉``*/
 bt[0] = (byte)(c >> 16);
               bt[1] = (byte)(c >> 8);   
 bt[2] = (byte)(c << 8);   
 bt[3] = (byte)(c & 0xff);   
         
 for(int i= 0;i<bt.length; i++  )
 System.out.println("------------" + bt[i]);  char rc = (char)((bt[0] << 16) |
                         (bt[1]<<8) | (bt[2]>>8) | (bt[3]));  long rlc = (long)rc;
 System.out.println("---------------rlc:" + rlc);
}         
打印结果是:------------0
------------115
------------0
-------------117
---------------rlc:65419

解决方案 »

  1.   


    你看看这样还行。    public static void main(String[] args) {
            long s = 29579;
            
            byte[] buf = new byte[4];
            for (int i = buf.length - 1; i >= 0; i--) {
                buf[i] = (byte) (s & 0x000000ff);
                s >>= 8;
            }
            
            for (int i = 0; i < buf.length; i++)
                System.out.println("------------" + buf[i]);
            
            long t = 0;
            for (int i = 0; i < buf.length; i++) {
                t <<= 8;
                t |= (buf[i] & 0x000000ff);
            }
            
            System.out.println("---------------rlc:" + t);
        }
      

  2.   

    自己顶一个。
    char c = 'L';
            byte [] b = new byte [ 2 ];
            b[ 0 ] = ( byte )(c & 0xFF);
            b[ 1 ] = ( byte )((c & 0xFF00) >> 8);
            char cr = ( char )(b[ 1 ] << 8 | (b[ 0 ] & 0xFF));
            System.err.println( cr );