Convert float[] to byte[] to float[] again

前端 未结 8 1604
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 15:17

So what I\'m trying to do here is get a float[], convert it to byte[], send it through the network as a datagram packet and then convert it back to

相关标签:
8条回答
  • 2020-12-31 16:13

    Use Float.floatToIntBits() to extract the bit-value of the float as an integer, then use BigInteger.toByteArray() to make a byte[]. This can be reversed using the BigInteger constructor that takes a byte[] argument, and then Float.intBitsToFloat().

    0 讨论(0)
  • 2020-12-31 16:15

    This is more for my future reference than anything else.

    public static byte[] floatToByte(float[] input) {
        byte[] ret = new byte[input.length*4];
        for (int x = 0; x < input.length; x++) {
            ByteBuffer.wrap(ret, x*4, 4).putFloat(input[x]);
        }
        return ret;
    }
    
    public static float[] byteToFloat(byte[] input) {
        float[] ret = new float[input.length/4];
        for (int x = 0; x < input.length; x+=4) {
            ret[x/4] = ByteBuffer.wrap(input, x, 4).getFloat();
        }
        return ret;
    }
    

    Can be reduced to a single line like https://stackoverflow.com/a/44104399/322017.

    0 讨论(0)
提交回复
热议问题