开发者社区> 问答> 正文

[@小川游鱼][¥20]Java 中怎样将 bytes 转换为 long 类型?

问题来自Java技术沙龙的李博
Java线下沙龙报名链接:https://yq.aliyun.com/activity/796

展开
收起
李博 bluemind 2018-12-13 14:19:48 2556 0
3 条回答
写回答
取消 提交回答
  • com.google.common.primitives.fromByteArray(xxx)

    2019-07-17 23:20:38
    赞同 展开评论 打赏
  • 这个人很懒,什么都没有留下。

    这样是否题目要求的呢?

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

    }

    2019-07-17 23:20:38
    赞同 展开评论 打赏
  • JAVA程序媛,欢迎交流!
        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();
        }
    2019-07-17 23:20:38
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载