Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

java - How to convert a float into a byte array and vice versa?

I am trying to convert a float into a primitive byte[] and vice versa:

public byte[] floatToByteArray(final float value)
{
    return new byte[]
    {
        (byte) (value >> 56),
        (byte) (value >> 48),
        (byte) (value >> 40),
        (byte) (value >> 32),
        (byte) (value >> 24),
        (byte) (value >> 16),
        (byte) (value >> 8),
        (byte) (value)
    };
}

Oddly enough, when I try to shift the newly allocated byte[] back into a float, the result is nothing but rubbish.

However, it would appear as if the same algorithm works just fine when I use the primitive long data type as argument instead.

public byte[] longToByteArray(final long value)
{
    return new byte[]
    {
        (byte) (value >> 56),
        (byte) (value >> 48),
        (byte) (value >> 40),
        (byte) (value >> 32),
        (byte) (value >> 24),
        (byte) (value >> 16),
        (byte) (value >> 8),
        (byte) (value)
    };
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use these instead.

public static byte [] long2ByteArray (long value)
{
    return ByteBuffer.allocate(8).putLong(value).array();
}

public static byte [] float2ByteArray (float value)
{  
     return ByteBuffer.allocate(4).putFloat(value).array();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...