You don't need to store all values. Process bits from to . When computing layer , you only need layer . Better: update in-place.
Start with . For each bit from to , update: if bit is set in mask, add to . The order matters: process masks with bit set after masks without it, or iterate masks in increasing order. This keeps is from layer when you read it.