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

前端 未结 8 1651
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  梦毁少年i
    2020-12-31 16:04

    Sender:

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    // byteBuffer reused for every element in floatArray
    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    // go through the elements in the float array writing its
    // byte equivalent  to the stream
    for(float element : floatArray) {
      byteBuffer.clear();
      byteBuffer.putFloat(element)
      byteStream.write(byteBuffer.array());
    }
    
    // Logic for sending bytestream's bytes as datagram packet
    // can get byte[] from steam by: byteStream.toByteArray();
    

    Receiver:

    ArrayList receivedValues = new ArrayList();
    ByteBuffer byteBuffer = ByteBuffer.wrap(receivedBytes);
    
    // while there is still 4 bytes left on the byte buffer
    // grab the next float and add it to the received list
    int position = 0;
    while(byteBuffer.capactiy - position >= 4) {
      receivedValues.add(byteBuffer.getFloat(position));
      position += 4;
    }
    
    float[] result = new float[receivedValues.count];
    return receivedValues.toArray(new float[receivedValues.size()]);
    

提交回复
热议问题