본문 바로가기

Programming/java

byte to long conversion

package handler.file;


public class ByteHandler {

/**

long -> byte array

* @param data

* @return

*/


public static byte[] toByte(long data) {

 return new byte[] {

  (byte)((data >> 56) & 0xff),

  (byte)((data >> 48) & 0xff),

  (byte)((data >> 40) & 0xff),

  (byte)((data >> 32) & 0xff),

  (byte)((data >> 24) & 0xff),

  (byte)((data >> 16) & 0xff),

  (byte)((data >> 8) & 0xff),

  (byte)((data >> 0) & 0xff),

  };

}


/**

long array -> byte array

* @param data

* @return

*/

public static byte[] toByte(long[] data) {

 if (data == null) 

  return null;

 byte[] bytes = new byte[data.length * 8];

 for (int i = 0; i < data.length; i++)

  System.arraycopy(toByte(data[i]), 0, bytes, i * 8, 8);

 

 return bytes;



/**

byte array -> long

* @param data

* @return

*/

public static long toLong(byte[] data) {

 if (data == null || data.length != 8) 

  return 0x0;

  

 return (long)((long)(0xff & data[0]) << 56 | 

  (long)(0xff & data[1]) << 48 |

  (long)(0xff & data[2]) << 40 |

  (long)(0xff & data[3]) << 32 |

  (long)(0xff & data[4]) << 24 |

  (long)(0xff & data[5]) << 16 |

  (long)(0xff & data[6]) << 8 |

  (long)(0xff & data[7]) << 0 );

}

public static void main(String[] args) {

 long longNum = 325351L;

 System.out.println(toLong(toByte(longNum)));

  }

}


출처 : http://www.sjava.net/111


'Programming > java' 카테고리의 다른 글

Java의 리플렉션 API  (0) 2013.01.18
JNI 네이밍 규약  (0) 2012.11.13
자바로 소수점 반올림하기  (1) 2012.04.10
소수점 올림  (0) 2011.11.14
디렉토리 지우기  (0) 2011.10.16