Java:字节到浮点数/整数

发布于 2024-10-08 13:40:32 字数 180 浏览 2 评论 0 原文

我有一个字节数组通过 UDP 从 x 平面发送。字节 (4) 都是浮点数或整数...... 我尝试将它们转换为浮点数,但到目前为止还没有运气......

示例数组: 字节数据[41] = {-66,30,73,0};

如何将 4 个字节转换为 int 或 float 并且 float 不使用 8 个字节?

I have a byte array sent via UDP from x-plane. The bytes (4) are all floats or integers…
I tried to cast them to floats but no luck so far…

Example array:
byte data[41] = {-66,30,73,0};

How do I convert 4 bytes into int or float and doesn't float use 8 bytes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

岛歌少女 2024-10-15 13:40:32

注意:我推荐下面@Ophidian的ByteBuffer方法,它比这。然而,这个答案有助于理解正在进行的位算术。

我不知道您数据的字节序。您基本上需要根据字节的顺序将字节转换为 int 类型,例如:

int asInt = (bytes[0] & 0xFF) 
            | ((bytes[1] & 0xFF) << 8) 
            | ((bytes[2] & 0xFF) << 16) 
            | ((bytes[3] & 0xFF) << 24);

然后您可以使用以下方法转换为 float:

float asFloat = Float.intBitsToFloat(asInt);

这基本上是 DataInputStream 在幕后所做的事情,但它假设您的字节按一定顺序排列。

编辑 - 关于按位或

OP 要求澄清按位或在这种情况下的作用。虽然这是一个更大的主题,可能需要更好地独立研究,但我将简要介绍一下。 Or (|) 是按位运算符,其结果是通过对两个操作数中的每个位进行单独或运算得到的位集。

例如(二进制)

   10100000
|  10001100
-----------
   10101100

当我建议在上面使用它时,它涉及将每个字节移动到 int 中的唯一位置。因此,如果您有字节 {0x01, 0x02, 0x03, 0x04},其二进制为 {00000001, 00000010, 00000011, 00000100},您将得到以下结果

                                  0000 0001   (1)
                        0000 0010             (2 <<  8)
              0000 0011                       (3 << 16)
  | 0000 0100                                 (4 << 24)
  --------------------------------------------------------
    0000 0100 0000 0011 0000 0010 0000 0001   (67 305 985)

:将两个数字或在一起,您知道两者中都没有设置两个相应的位(就像这里的情况),按位或与加法相同。

另请参阅

Note: I recommend @Ophidian's ByteBuffer approach below, it's much cleaner than this. However this answer can be helpful in understanding the bit arithmetic going on.

I don't know the endianness of your data. You basically need to get the bytes into an int type depending on the order of the bytes, e.g.:

int asInt = (bytes[0] & 0xFF) 
            | ((bytes[1] & 0xFF) << 8) 
            | ((bytes[2] & 0xFF) << 16) 
            | ((bytes[3] & 0xFF) << 24);

Then you can transform to a float using this:

float asFloat = Float.intBitsToFloat(asInt);

This is basically what DataInputStream does under the covers, but it assumes your bytes are in a certain order.

Edit - On Bitwise OR

The OP asked for clarification on what bitwise OR does in this case. While this is a larger topic that might be better researched independently, I'll give a quick brief. Or (|) is a bitwise operator whose result is the set of bits by individually or-ing each bit from the two operands.

E.g. (in binary)

   10100000
|  10001100
-----------
   10101100

When I suggest using it above, it involves shifting each byte into a unique position in the int. So if you had the bytes {0x01, 0x02, 0x03, 0x04}, which in binary is {00000001, 00000010, 00000011, 00000100}, you have this:

                                  0000 0001   (1)
                        0000 0010             (2 <<  8)
              0000 0011                       (3 << 16)
  | 0000 0100                                 (4 << 24)
  --------------------------------------------------------
    0000 0100 0000 0011 0000 0010 0000 0001   (67 305 985)

When you OR two numbers together and you know that no two corresponding bits are set in both (as is the case here), bitwise OR is the same as addition.

See Also

紫南 2024-10-15 13:40:32

您可能想使用 java.nio.ByteBuffer< /a>.它有很多方便的方法来从字节数组中提取不同类型,并且还应该为您处理大多数字节顺序问题(包括在必要时切换字节顺序)。

byte[] data = new byte[36]; 
//... populate byte array...

ByteBuffer buffer = ByteBuffer.wrap(data);

int first = buffer.getInt();
float second = buffer.getFloat();

它还具有将字节数组转换为 int 数组的奇特功能(通过 IntBuffer)或浮点数组(通过 FloatBuffer 来自 asFloatBuffer() 方法)如果您知道输入实际上都是一种类型。

You probably want to make use of java.nio.ByteBuffer. It has a lot of handy methods for pulling different types out of a byte array and should also handle most issues of endianness for you (including switching the byte order if necessary).

byte[] data = new byte[36]; 
//... populate byte array...

ByteBuffer buffer = ByteBuffer.wrap(data);

int first = buffer.getInt();
float second = buffer.getFloat();

It also has fancy features for converting your byte array to an int array (via an IntBuffer from the asIntBuffer() method) or float array (via a FloatBuffer from the asFloatBuffer() method) if you know that the input is really all of one type.

独闯女儿国 2024-10-15 13:40:32

使用 DataInputStream 如下:

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
    float f = dis.readFloat();

    //or if it's an int:        
    int i = dis.readInt();

Use a DataInputStream as follows:

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
    float f = dis.readFloat();

    //or if it's an int:        
    int i = dis.readInt();
若相惜即相离 2024-10-15 13:40:32

您不能将它们直接转换为 float/int。您必须将字节转换为 int 或 float。

这是一种简单的方法:

byte [] data = new byte[] {1,2,3,4};
ByteBuffer b = ByteBuffer.wrap(data);
System.out.println(b.getInt());
System.out.println(b.getFloat());

这里有一个合理的讨论:

You cannot just cast them into a float/int. You have to convert the bytes into an int or float.

Here is one simple way to do it:

byte [] data = new byte[] {1,2,3,4};
ByteBuffer b = ByteBuffer.wrap(data);
System.out.println(b.getInt());
System.out.println(b.getFloat());

There is a reasonable discussion here:

http://www.velocityreviews.com/forums/t129791-convert-a-byte-array-to-a-float.html

魂牵梦绕锁你心扉 2024-10-15 13:40:32

在我看来,ByteBuffer 方法更好,您可以指定数据的包装位置(来自哪个字节索引,此处为 0)以及字节序(此处为 BIG_ENDIAN)。

try {
    float result = ByteBuffer.wrap(data, 0, 4).order(BIG_ENDIAN).getFloat();
} catch (IndexOutOfBoundsException exception) {
    // TODO: handle exception
}

类似于 getFloat() 的函数存在于 Int、Short、Long...

In my opinion the ByteBuffer approach is better, you can specify where the data is wrapped (from which byte index, here 0) and also the endianness (here BIG_ENDIAN).

try {
    float result = ByteBuffer.wrap(data, 0, 4).order(BIG_ENDIAN).getFloat();
} catch (IndexOutOfBoundsException exception) {
    // TODO: handle exception
}

Functions similar to getFloat() exist for Int, Short, Long...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文