Home > Software design >  How can this formula to swizzle rows be simplified?
How can this formula to swizzle rows be simplified?

Time:02-03

The problem is quite simple to understand but solving it was not as easy as it sounded at first.

Let's assume the following, an image that is 8*4, normal order is easy, you return the pixel index:

// 00 01 02 03 04 05 06 07
// 08 09 10 11 12 13 14 15
// 16 17 18 19 20 21 22 23
// 24 25 26 27 28 29 30 31

Now suppose you want to swizzle rows like so:

// 00 01 02 03 04 05 06 07
// 16 17 18 19 20 21 22 23
// 08 09 10 11 12 13 14 15
// 24 25 26 27 28 29 30 31

I solved it, not without trouble to be honest, with the following formula:

index / 8 % 2 * 16   index / 16 * 8   index % 8

Isn't there a simpler formula to get the same result?

CodePudding user response:

Assuming / and % return the quotient and remainder in the Euclidean division:

The classic ordering can be obtained as:

row = n / 8
col = n % 8

And the swizzled ordering can be obtained as:

col = n % 8
old_row = n / 8
new_row = 2 * (old_row / 2)   (1 - (old_row % 2))

Explanation:

  • 2 * (old_row / 2) groups the rows two by two;
  • (1 - (old_row % 2)) swaps row 0 and row 1 of each group.
  • Related