Search code examples
javabytebit

Increment a counter inside a byte array


I have an array of 5 bytes (fixed length). First 21 bits represent a counter and the rest 19 some id. I need to increment the counter by one. How do I do that?


Solution

  • This answer is based on the memory layout as I understand it from the OP's comments:

    array[0]: bits 0..7 are counter bits 0..7 (lsb)
    array[1]: bits 0..7 are counter bits 8..15
    array[2]: bits 0..4 are counter bits 16..20 (msb)
              bits 5..7 are part of the id
    array[3]: bits 0..7 are part of the id
    array[3]: bits 0..7 are part of the id
    

    Then

    int byte0 = (int) array[0] & 0xff;
    int byte1 = (int) array[1] & 0xff;
    int byte2 = (int) array[2] & 0x1f;
    
    int count = byte0 | (byte1 << 8) | (byte2 << 16);
    
    count = (count+1) & 0x1fffff;
    
    array[0] = (byte) (count & 0x0000ff);
    array[1] = (byte) ((count & 0x00ff00) >> 8);
    array[2] = (array[2] & 0xe0) | (byte) ((count & 0x1f0000) >> 16);
    

    should do the trick.