[轉]java中long,int,short與byte數組之間的轉換


//long類型轉成byte數組  
 
public static byte [] longToByte ( long number ) {  
       
long temp = number ;  
       
byte [] b = new byte [ 8 ];  
       
for ( int i = 0 ; i < b . length ; i ++) {  
            b
[ i ] = new Long ( temp & 0xff ). byteValue (); //  
將最低位保存在最低位  
            temp
= temp >> 8 ; // 向右移8位  
       
}  
       
return b ;  
   
}  
    
   
//byte數組轉成long  
   
public static long byteToLong ( byte [] b ) {  
       
long s = 0 ;  
       
long s0 = b [ 0 ] & 0xff ; // 最低位  
       
long s1 = b [ 1 ] & 0xff ;  
       
long s2 = b [ 2 ] & 0xff ;  
       
long s3 = b [ 3 ] & 0xff ;  
       
long s4 = b [ 4 ] & 0xff ; // 最低位  
       
long s5 = b [ 5 ] & 0xff ;  
       
long s6 = b [ 6 ] & 0xff ;  
       
long s7 = b [ 7 ] & 0xff ;  
 
       
// s0不變  
        s1
<<= 8 ;  
        s2
<<= 16 ;  
        s3
<<= 24 ;  
        s4
<<= 8 * 4 ;  
        s5
<<= 8 * 5 ;  
        s6
<<= 8 * 6 ;  
        s7
<<= 8 * 7 ;  
        s
= s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7 ;  
       
return s ;  
   
}  
 
/** 
     * 注釋:int到字節數組的轉換! 
     * 
     * @param number 
     * @return 
     */
 
   
public static byte [] intToByte ( int number ) {  
       
int temp = number ;  
       
byte [] b = new byte [ 4 ];  
       
for ( int i = 0 ; i < b . length ; i ++) {  
            b
[ i ] = new Integer ( temp & 0xff ). byteValue (); //  
將最低位保存在最低位  
            temp
= temp >> 8 ; // 向右移8位  
       
}  
       
return b ;  
   
}  
 
   
/** 
     * 注釋:字節數組到int的轉換! 
     * 
     * @param b 
     * @return 
     */
 
   
public static int byteToInt ( byte [] b ) {  
       
int s = 0 ;  
       
int s0 = b [ 0 ] & 0xff ; // 最低位  
       
int s1 = b [ 1 ] & 0xff ;  
       
int s2 = b [ 2 ] & 0xff ;  
       
int s3 = b [ 3 ] & 0xff ;  
        s3
<<= 24 ;  
        s2
<<= 16 ;  
        s1
<<= 8 ;  
        s
= s0 | s1 | s2 | s3 ;  
       
return s ;  
   
}  
 
   
/** 
     * 注釋:short到字節數組的轉換! 
     * 
     * @param s 
     * @return 
     */
 
   
public static byte [] shortToByte ( short number ) {  
       
int temp = number ;  
       
byte [] b = new byte [ 2 ];  
       
for ( int i = 0 ; i < b . length ; i ++) {  
            b
[ i ] = new Integer ( temp & 0xff ). byteValue (); //  
將最低位保存在最低位  
            temp
= temp >> 8 ; // 向右移8位  
       
}  
       
return b ;  
   
}  
 
   
/** 
     * 注釋:字節數組到short的轉換! 
     * 
     * @param b 
     * @return 
     */
 
   
public static short byteToShort ( byte [] b ) {  
       
short s = 0 ;  
       
short s0 = ( short ) ( b [ 0 ] & 0xff ); // 最低位  
       
short s1 = ( short ) ( b [ 1 ] & 0xff );  
        s1
<<= 8 ;  
        s
= ( short ) ( s0 | s1 );  
       
return s ;  
   
}

來自:http://hi.baidu.com/menglinxi_a/blog/item/bbb061dcce494bb9cd11668b.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM