long 与byte类型间相互转换

package test;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class Stest {
public static void main(String args[]) throws UnsupportedEncodingException {
// test for convertLongToBytes
long e = -1212;
byte[] b = convertLongToBytes(e);
for (byte c : b) {
System.out.println(c);
}
// test for convertLongToBytes
long ret = convertBytesToLong(b);
System.out.println(ret);

}
public static long convertBytesToLong(byte[] b) {
ByteBuffer buf = ByteBuffer.wrap(b);
return buf.getLong();
}

public static byte[] convertLongToBytes(long l) {
byte b[] = new byte[Long.SIZE];
ByteBuffer buf = ByteBuffer.wrap(b);
buf.putLong(l);
buf.flip();
return buf.array();
}
}

posted @ 2015-11-10 12:40  lele88lala  阅读(2559)  评论(0编辑  收藏  举报