Convert long, long[] with byte array

long -> byte array

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

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

public static long toLong(byte[] data) {
  if (data == null || data.length != 8) 
   return 0×0;

  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 );
 }

Convert long, long[] with byte array”에 대한 1개의 생각

답글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다.