How to write a large int as as bytes

edited December 2015 in How To...

Hi, I need to send the value 115200 over serial to an external device that accepts the format 0x00, 0x00, 0x00, 0x00, and I have no idea how to convert it into that format. Any advice would be much appriciated. Thanks

Answers

  • Step one would be to understand exactly how that format maps to the value. Does the documentation for the device explain what that format means?

  • edited February 2016 Answer ✓

    Converting 1 int to 4 byte (big-endian) values is like extracting aRGB properties from 1 color: :ar!

    /**
     * aRGB_Shifting_Conversion (v1.0)
     * GoToLoop (2015-Nov-05)
     *
     * forum.Processing.org/two/discussion/13411/how-to-write-a-large-int-as-as-bytes
     * forum.Processing.org/two/discussion/13792/color-bit-shifting
     * forum.Processing.org/two/discussion/14814/how-to-translate-byte-to-pimage
     */
    
    final byte[] output = new byte[4];
    int input = 115200;
    
    void setup() {
      println(input, binary(input));
      to_aRGB_array(input, output);
      println(output);
      exit();
    }
    
    static final byte[] to_aRGB_array(color c, byte... target) {
      byte a = (byte) (c >>> 030);
      byte r = (byte) (c >>  020 & 0xff);
      byte g = (byte) (c >>  010 & 0xff);
      byte b = (byte) (c         & 0xff);
    
      if (target == null || target.length < 4)  return new byte[] {a, r, g, b};
    
      target[0] = a;
      target[1] = r;
      target[2] = g;
      target[3] = b;
    
      return target;
    }
    
  • Thank you! this helped a lot!

Sign In or Register to comment.