Unpacking UDP Packet - byte to float

I am receiving this message from another app via a udp socket (hypermedia.net). I'd like to convert message after blank to a floating point value.

receive: "56871833174353 -0.095239157733537" from 192.168.178.52 on port 50396

void receive( byte[] data, String ip, int port ) {
  data = subset(data, 0, data.length-2);
  String message = new String( data );
  println( "receive: \""+message+"\" from "+ip+" on port "+port );
}

Answers

  • edited November 2015

    Ok, I have found a solution:

    void receive( byte[] data, String ip, int port ) {
      data = subset(data, 0, data.length-2);
      String message = new String( data );
      String[] nums = split(message, ' ');
      float slope = Float.parseFloat(nums[1]);
      println(slope);
    }
    
  • edited November 2015 Answer ✓
    // forum.processing.org/two/discussion/13598/unpacking-udp-packet-byte-to-float
    // GoToloop (2015-Nov-22)
    
    byte[] received = { // "56871833174353 -0.095239157733537"
      '5', '6', '8', '7', '1', '8', '3', '3', '1', '7', '4', '3', '5', '3', 
      ' ', '-', '0', '.', 
      '0', '9', '5', '2', '3', '9', '1', '5', '7', '7', '3', '3', '5', '3', '7'
    };
    
    void setup() {
      float slope = parseSlope(received);
      println(slope); // gets -0.095239155 from -0.095239157733537
      exit();
    }
    
    static final float parseSlope(byte... data) {
      return float(splitTokens(new String(data).trim())[1]);
    }
    
Sign In or Register to comment.