Implementing an L-System conversion from R2 to R1 for symmetric, square matrices
I've defined the following function in R

State 0 indicates that one is located within a right-angle region

State 1 indicates that one is located within a Hilbert curve

State 2 indicates that one is located within a wedge region



rot &lt;- function(n, x, y, rx, ry) {
  if (ry == 1) {
    if (rx == 0) {
      x &lt;&lt;- n-1 - x
      y &lt;&lt;- n-1 - y
    }

    temp &lt;- x
    x &lt;&lt;- y
    y &lt;&lt;- temp
  }
}




xy2d &lt;- function(n, x, y) {
  # rx = x region (right = 1, left equals 0) 
  # ry = y region (top = 1, bottom = 0)
  # s = half the dimension
  # d = linear coordinate value
  d=0L
  state = 0L
  for (s in 2L^(log2(n/2L):0)) {
    rx = bitwAnd(x, s) &gt; 0
    ry = bitwAnd(y, s) &gt; 0
    if (state == 0) {
      # *--2  | 0  -&gt;  *--2   | 1 -&gt; 0--3   | 2 -&gt; *--2   |  
      # 0--1  |        0--1   |      1--2   |      1--0   |

      # if x on right region, add lower left triangle (region 0)
      #      (s * (s + 1) / 2) * rx
      # if y on upper region, add lower right square as well (both regions 0 and 1)
      #     (s * s) * ry
      d = d + (s * (s + 1) / 2) * rx + (s * s) * ry
      d
      # change the state
      #  rx  ry | (rx + ry)
      #  0   0  |  0
      #  1   0  |  1
      #  1   1  |  2
      state = rx + ry
      state
    }else if (state == 1) {
      # 0--3  | 0  -&gt;  0--1   | 1,2 -&gt; 0--3   | 3 -&gt; 2--3   |  
      # 1--2  |        3--2   |        1--2   |      1--0   |


      # Determine how many squares to add
      # equals number in s-by-s square times it's order in the curve
      #  rx  ry | (3 * rx) ^ (1 - ry)
      #  0   1  |  0 ^ 0 = [00] ^ [00] = 00 = 0
      #  0   0  |  0 ^ 1 = [00] ^ [01] = 01 = 1
      #  1   0  |  3 ^ 1 = [11] ^ [01] = 10 = 2
      #  1   1  |  3 ^ 0 = [11] ^ [00] = 11 = 3
      d = d + s * s * bitwXor(3 * rx, 1 - ry)
      d
      # ROTATE
      rot(n, x, y, rx, ry)
      x
      y

    }else if (state == 2) {
      # *--2  | 0  -&gt;  2--1   | 1 -&gt; *--2   | 3 -&gt; *--2   |  
      # 1--0  |        3--0   |      1--0   |      0--1   |

      d = d + (s * s) * (rx == ry) + (s * (s + 1) / 2) * (rx == 1 &amp;&amp; ry == 1)

      #  rx  ry |  Target | state - (rx + ry)
      #_________|_________|__________________
      #  1   0  |  1      | 2 - (1 + 0) = 1
      #  0   0  |  2      | 2 - (0 + 0) = 2
      #  1   1  |  0      | 2 - (1 + 1) = 0

      # new_state = current_state - (rx + ry)
      state = 2 - (rx + ry)
      if (state == 1) {
        # If the state goes from state-2 to state-1, then rotate the hilbert 
        # curve 180 degrees (i.e. reflect horizonally and vertically)
        x &lt;- n-1 - x
        y &lt;- n-1 - y
      }
    }
  }
  return(d)
}




xy2d(8,5,0)

[1] 16
```