本文介绍了在 Java 中将字节数组转换为整数,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Java 中将一些数据存储到字节数组中.基本上只是数字,每个数字最多可占用 2 个字节.

I want to store some data into byte arrays in Java. Basically just numbers which can take up to 2 Bytes per number.

我想知道如何将整数转换为 2 字节长的字节数组,反之亦然.我在谷歌上找到了很多解决方案,但大多数都没有解释代码中发生的事情.有很多变化的东西我不太明白,所以我希望得到一个基本的解释.

I'd like to know how I can convert an integer into a 2 byte long byte array and vice versa. I found a lot of solutions googling but most of them don't explain what happens in the code. There's a lot of shifting stuff I don't really understand so I would appreciate a basic explanation.

推荐答案

使用 java.nio 命名空间,特别是 ByteBuffer.它可以为您完成所有工作.

Use the classes found in the java.nio namespace, in particular, the ByteBuffer. It can do all the work for you.

byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1

ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }

这篇关于在 Java 中将字节数组转换为整数,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:59