Created
          January 25, 2016 08:28 
        
      - 
      
 - 
        
Save antoniomaria/598ea89d54accef1a1f5 to your computer and use it in GitHub Desktop.  
    Java split bytes array into chunks
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | byte[] data = { 2, 3, 5, 7, 8, 9, 11, 12, 13 }; | |
| int blockSize = 3; | |
| int blockCount = (data.length + blockSize - 1) / blockSize; | |
| byte[] range = null; | |
| for (int i = 1; i < blockCount; i++) { | |
| int idx = (i - 1) * blockSize; | |
| range = Arrays.copyOfRange(data, idx, idx + blockSize); | |
| System.out.println("Chunk " + i + ": " Arrays.toString(range)); | |
| } | |
| // Last chunk | |
| int end = -1; | |
| if (data.length % blockSize == 0) { | |
| end = data.length; | |
| } else { | |
| end = data.length % blockSize + blockSize * (blockCount - 1); | |
| } | |
| range = Arrays.copyOfRange(data, (blockCount - 1) * blockSize, end); | |
| System.out.println("Chunk " + blockCount + ": " Arrays.toString(range)); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment