Morton Encoding
by Nick Karnik
HTML
<input id="itemindex" style="width:200px" />
<button onclick="encode(itemindex.value)">Index to Row,Col</button>
<input id="rowcol" style="width:200px" />
<button onclick="decode(rowcol.value)">Row,Col to Index</button>
<hr>
<textarea id="itemcontent" style="height:400px;width:300px"></textarea>
<textarea id="rowcolcontent" style="height:400px;width:300px"></textarea>
JavaScript
/*
* Decode
* Input: Row,Column (Comma separated integers)
* Output: Decimal row, Decimal Col => Binary row, Binary Col <==> Decimal Index, Binary Index
*/
function decode(pair) {
//Parse input
var row = parseInt(pair.split(",")[0], 10);
var col = parseInt(pair.split(",")[1], 10);
// Interleave Row and Column
var val = (((col & 1)) + ((col & 2) << 1) + ((col & 4) << 2) + ((col & 8) << 3) + ((col & 16) << 4) + ((col & 32) << 5) + ((col & 64) << 6) + ((col & 128) << 7) + ((col & 256) << 8) + ((col & 512) << 9) + ((col & 1024) << 10) + ((col & 2048) << 11) + ((col & 4096) << 12) + ((col & 8192) << 13) + ((col & 16384) << 14) + ((col & 32768) << 15)) +
// The line break in between is to separate the two dimensions
(((row & 1) << 1) + ((row & 2) << 2) + ((row & 4) << 3) + ((row & 8) << 4) + ((row & 16) << 5) + ((row & 32) << 6) + ((row & 64) << 7) + ((row & 128) << 8) + ((row & 256) << 9) + ((row & 512) << 10) + ((row & 1024) << 11) + ((row & 2048) << 12) + ((row & 4096) << 13) + ((row & 8192) << 14) + ((row & 16384) << 15) + ((row & 32768) << 16));
//Output
// rowcolcontent.value += row + ", " + col + " => " + row.toString(2) + ", " + col.toString(2) + " <==> " + val + ", " + val.toString(2) + "\n";
rowcolcontent.value += row + ", " + col + " => " + val + "\n";
}
/*
* Encode
* Input: Integer
* Output: Decimal => Binary <==> Decimal Row, Decimal Col => Binary Row, Binary Col
*/
function encode(n) {
// itemcontent.value = "";
// //Encode and output every number from 0 to max-1
// for (n = 0; n < max; n++) {
//Row
var row = (((n & 2) >> 1) + ((n & 8) >> 2) + ((n & 32) >> 3) + ((n & 128) >> 4) + ((n & 512) >> 5) + ((n & 2048) >> 6) + ((n & 8192) >> 7) + ((n & 32768) >> 8) + ((n & 131072) >> 9) + ((n & 524288) >> 10) + ((n & 2097152) >> 11) + ((n & 8388608) >> 12) + ((n & 33554432) >> 13) + ((n & 134217729) >> 14) + ((n & 536870912) >> 15) + ((n & 2147483648) >> 16));
//Column
...