4字节无符号int转long

加盾男爵 2020-05-21 05:03:40
安卓连接设备,设备会发送消息,设备使用C语言,其中一个字段为4字节,无符号int,最初使用

DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(bytes));
int a = dataInputStream.readInt();

来转化,但后来设备发过来的无符号int的值会超过java的int最大值,所以必须把这4个字节转化为long,既
0xFFFFFFFF,这4个字节必须转化为4294967295,如果使用上面代码,结果为1

测试代码如下

ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.put((byte)255);
buffer.put((byte)255);
buffer.put((byte)255);
buffer.put((byte)255);
Log.d("TestFunc","结果:"+byteArrayToLong(buffer.array()));

该代码我希望的打印结果是

“结果:4294967295”

受安卓版本影响,无法使用Long的静态函数转化(该函数需要api26,而目标手机要求最低21),所以只能自己定义一个byteArrayToLong()
函数,网上找了一下午,没有找到正确答案,自己想了多个办法,都没有办法得出正确结果,比如下面,结果是1

byteArrayToLong(){
long a = 0;
for(int i = 0 ; i < 4 ; ++i){
a <<= 8;
a |= bytes[i];
}
return a;
}


请问有没有把4字节(无符号int)转化为long的
...全文
752 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
gd6321374 2020-05-25
  • 打赏
  • 举报
回复
又或则 try { uid = (uidStream[3] & 0xFF); uid <<= 8; uid += (uidStream[2] & 0xFF); uid <<= 8; uid += (uidStream[1] & 0xFF); uid <<= 8; uid += (uidStream[0] & 0xFF); return String.format("%d", uid); } catch (Exception e) { e.printStackTrace(); return null; }
gd6321374 2020-05-25
  • 打赏
  • 举报
回复
估计你不是做底层的, public static int byteToInt(byte[] data) { int value = 0, val = 0; val = data[0]; value = (val & 0xFF); value <<= 8; val = data[1]; value = value + (val & 0xFF); return value; }
王能 2020-05-24
  • 打赏
  • 举报
回复
接分接分接分
加盾男爵 2020-05-21
  • 打赏
  • 举报
回复
解决了,来人接分

return (long) (b4 & 0xFF) << 24 | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
即可

80,471

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧