maintain leading zeros?

// Called each time a new packet arrives
void packetEvent(CarnivorePacket p) {
  int i = 0;  // index
  while ( i < p.data.length) {
    // limit to HTTP traffic
    if (p.senderPort == 80 || p.senderPort == 443) {

      // grab three available bytes
      if ( (i + 2) < p.data.length) {

        // if there's enough room to grab 3 more bytes
        // attach a number on the left side so 001 is like 1001, so as not to fall off
        num1 = binary(p.data[i])) 

        // just add 'em up!
        int fullnum = int(binary(p.data[i])) + int(binary(p.data[i + 1])) + int(binary(p.data[i + 2]));
        i += 3;  // set index to next number after this set
        println(fullnum);

      } else {
        i++;  // just go on to the end if not
      }

    }
    i++;

  }
}

This works pretty well, with output like:

20221122
23111003
21111111
22101203
10100131
3300012 --- problem!
21121030
13111222

Since some bytes will have leading zeros after being added together, I get cut-off numbers like this. The end result is to use these numbers to control LEDs (0 = nothing, 1 = red, 2 = green, so on). I suppose I could convert it to a string to take care of this, but that sounds expensive. Thoughts?

Answers

  • The issue here is that the int type automatically removes excessive zeros, as you may already know. One thought would be to have the LEDs read the numbers from right to left and have it interpret any leftover LEDs as 0.

  • Ah yes, indeed.

    Something like...

    void sendOut(int nums) {
      // the logic is to mod each number and divide to single out the digits so that they can be sent out individually
      int[] digs = new int[8];  // create space for 8 digits
      digs[7] = nums % 10;       // slice off the last digit (far right) for the last lantern (far right)
    
      digs[6] = (nums % 100)/10;       // ...
    
      digs[5] = (nums % 1000)/100;       // ...
    
      digs[4] = (nums % 10000)/1000;       // ...
    
      digs[3] = (nums % 100000)/10000;       // ...
    
      digs[2] = (nums % 1000000)/100000;       // ...
    
      digs[1] = (nums % 10000000)/1000000;       // ...
    
      digs[0] = (nums % 100000000)/10000000;       // ...
    
  • The zeroes are there (there is an infinity of them before the digits...) but not displayed by println(). You can use nf() to format an integer to a string with leading zeroes.

Sign In or Register to comment.