如何在Java中将字节转换为long? [英] How do I convert a byte to a long in Java?

查看:125
本文介绍了如何在Java中将字节转换为long?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从硬件设备读取8个字节的数据。我需要将它们转换为数值。我想我想将它们转换为长度,因为它应该适合8个字节。我对Java和低级数据类型操作不是很熟悉。我似乎有两个问题(除了几乎没有相关硬件的文档),字节期望是无符号的,所以我不能进行直接整数转换。我不确定它们是什么字节序。

I am reading 8 bytes of data in from a hardware device. I need to convert them into a numeric value. I think I want to convert them to a long as that should fit 8 bytes. I am not very familiar with Java and low level data type operations. I seem to have two problems (apart from the fact there is almost no documentation for the hardware in question), The bytes are expecting to be unsigned, so I can't do a straight integer conversion. I am not sure what endianness they are.

任何建议都将受到赞赏。

Any advice would be appreciated.

结束了这个(取自一些我可能应该在一周前读过的一些源代码):

Ended up with this (taken from some source code I probably should have read a week ago):

public static final long toLong (byte[] byteArray, int offset, int len)
{
   long val = 0;
   len = Math.min(len, 8);
   for (int i = (len - 1); i >= 0; i--)
   {
      val <<= 8;
      val |= (byteArray [offset + i] & 0x00FF);
   }
   return val;
}


推荐答案

对于字节序,请测试你知道一些数字,然后你将使用字节移位将它们移动到长整数。

For the endianness, test with some numbers you know, and then you will be using a byte shifting to move them into the long.

你可能会发现这是一个起点。
http://www.janeg.ca/scjp/oper/shift。 html

You may find this to be a starting point. http://www.janeg.ca/scjp/oper/shift.html

难点在于取决于结尾会改变你的方式,但你会改变24,16,8然后加上最后一个,基本上,如果做32位,但你会更长,所以只需做额外的转移。

The difficulty is that depending on the endianess will change how you do it, but you will shift by 24, 16, 8 then add the last one, basically, if doing 32 bits, but you are going longer, so just do extra shifting.

这篇关于如何在Java中将字节转换为long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆