问题来自Java技术沙龙的李博
Java线下沙龙报名链接:https://yq.aliyun.com/activity/796
这样是否题目要求的呢?
public class ByteUtil {
private static final long HEX_LONG = 0x0000000000000000L;
private static final byte HEX_BYTE = (byte) 0xff;
public static Long byteToLong(Byte[] bytes) {
if (bytes == null || bytes.length != 8) {
throw new RuntimeException("param error.");
}
long result = HEX_LONG;
for (int i = 0; i < bytes.length; i++) {
long tmp = Byte.toUnsignedLong(bytes[i]);
tmp <<= (56 - i * 8);
result = result | tmp;
// System.out.println(getLongHexStr(result));
}
return result;
}
public static String getLongHexStr(long x) {
StringBuilder sb = new StringBuilder();
for (int i = 63; i >= 0; i--) {
sb.append((x & 0x0000000000000001) == 1l ? "1" : "0");
x >>= 1;
}
return sb.reverse().toString();
}
public static Byte[] getBytesFromLong(Long x) {
Byte[] bytes = new Byte[8];
for (int i = 0; i < bytes.length; i++) {
bytes[bytes.length - 1 - i] = (byte) (x & 0x00000000000000ffL);
x >>= 8;
}
return bytes;
}
public static void main(String[] args) {
System.out.println(byteToLong(getBytesFromLong(1236786534l)));
System.out.println(byteToLong(getBytesFromLong(-1236786534l)));
System.out.println(byteToLong(getBytesFromLong(-0l)));
System.out.println(byteToLong(getBytesFromLong(0l)));
// System.out.println("Long.maxvalue=" + Long.MAX_VALUE + ",byteToLong="
// + byteToLong(
// new Byte[] { HEX_BYTE, HEX_BYTE, HEX_BYTE, HEX_BYTE, HEX_BYTE,
// HEX_BYTE, HEX_BYTE, HEX_BYTE, }));
}
}
public static long bytes2long(byte[] param) {
long result = 0;
if (param== null || param.length == 0) {
return result;
}
ByteBuffer buffer = ByteBuffer.wrap(param);
return buffer.getLong();
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。