msbTest
by mklemma
HTML
<div id="app"></div>
<input id="input" type="text" size="10" maxlength="20" value="243">
<button id="button">msb</button><br/>
<div id="binary"></div>
<div id="result"></div>
CSS
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
TypeScript
function toBinary(n: number): string {
let p = n.toString(2);
while (p.length < 16) p = "0" + p;
let s = "";
for (let i = 0; i < p.length; i++) {
if (i != 0 && i % 4 == 0) s += "_";
s += p[i];
}
return s;
}
function msb4(x: number) {
const kcopy = (x | 0b10000) * 0b00001000010000100001;
const msbflags = kcopy - 0b01000001000001000001;
const xdash = (msbflags & 0b10000100001000010000) >> 4;
const zurashiPlus = xdash * 0b00001000010000100001;
const msb = (zurashiPlus >> 15) & 0b11111;
return msb;
}
function computeY(x : number){
const xWithFlags = x | 0b1000100010001000;
const yWidthPaddings = (xWithFlags - 0b0001000100010001) & 0b1000100010001000;
const zurashiPlus = (yWidthPaddings >> 3) * 0b1001001001000;
const y = (zurashiPlus >> 12) & 0b1111;
return y;
}
function computeYdash(x : number){
const leftmostBits = x & 0b1000100010001000;
const zurashiPlus = (leftmostBits >> 3) * 0b1001001001000;
const ydash = (zurashiPlus >> 12) & 0b1111;
return ydash;
}
function msb16(x: number) {
if(x == 0) return 0;
if(x >= 65536) throw Error("0 <= x < 65536");
const y = computeY(x);
const ydash = computeYdash(x);
const bitBlocks = y | ydash;
const msbBlockPos = msb4(bitBlocks);
const msbBlock = (x >> ((msbBlockPos - 1) * 4)) & 0b1111;
const msb = msb4(msbBlock) + ((msbBlockPos - 1) * 4);
return msb;
}
function msbButton(){
const p = parseInt(document.getElementById("input").value);
if(p < 0 || p >= 65536){
alert("0 < x <= 65536");
return;
}
const msb = msb16(p);
document.getElementById("binary").textContent = p.toString() + " = " + toBinary(p);
document.getElementById("result").textContent = "msb = " + msb.toString();
}
window.onload = ()=>{
document.getElementById("button").onclick = msbButton;
msbButton();
}