Skip to content

Instantly share code, notes, and snippets.

@cleverfox
Created February 23, 2018 11:35
Show Gist options
  • Save cleverfox/08f0b7cde3f6600f164853ca9a9002d2 to your computer and use it in GitHub Desktop.
Save cleverfox/08f0b7cde3f6600f164853ca9a9002d2 to your computer and use it in GitHub Desktop.
js address encoder
var makeCRCTable = function(){
var C;
var CrcTable = [];
for(var N =0; N < 256; N++){
C = N;
for(var k =0; k < 8; k++){
C = ((C&1) ? (0xEDB88320 ^ (C >>> 1)) : (C >>> 1));
}
CrcTable[N] = C;
}
return CrcTable;
}
var crc32 = function(Addr) {
var CrcTable = window.CrcTable || (window.CrcTable = makeCRCTable());
var Crc = 0 ^ (-1);
for (var i = 0; i < 8; i++ ) {
Crc = (Crc >>> 8) ^ CrcTable[(Crc ^ Addr[i]) & 0xFF];
}
return (Crc ^ (-1)) >>> 0;
};
var pad=function(Base, Num, Size) {
if(Base==26){
var A="A".charCodeAt(0),
B0=Num % 26,
B1=Math.floor(Num / 26);
return String.fromCharCode(B1+A)+String.fromCharCode(B0+A);
}else{
var S = Num.toString(Base);
while (S.length < Size) S = "0" + S;
return S;
}
}
var encode = function(Addr) {
// 100GGGGG GGGGGGGG GGGBBBBB BBBBBBBB BBBBBBBB AAAAAAAA AAAAAAAA AAAAAAAA
// 101BBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB AAAAAAAA AAAAAAAA AAAAAAAA
if(Addr[0]<128 || Addr[0]>191) throw "bad address";
var Address=Addr[7] | (Addr[6] << 8) | (Addr[5] << 16);
var Cs=crc32(Addr);
if(Addr[0] & 0x20){ //private
var Block=Addr[4] | (Addr[3] << 8) | (Addr[2] << 16) | (Addr[1] << 24) | ((0x1f & Addr[0]) << 32);
var TxtAddr=pad(16,Block,10)+pad(16,Address,6)+pad(16,Cs % 256,2);
return {
scope: "private",
csum: Cs % 100,
block: Block,
txt: TxtAddr,
addr: Address
}
}else{ //public
var Block=Addr[4] | (Addr[3] << 8) | ((0x1f & Addr[2]) << 16);
var Group=(Addr[2] | (Addr[1] << 8) | ((0x1f & Addr[0]) << 16)) >> 5;
var IntPart=Address | Block << 24;
var TxtAddr=pad(26,parseInt(Group / 100),2)+pad(10,Group % 100,2)+pad(10,IntPart,14)+pad(10,Cs % 100,2);
return {
scope: "public",
addr: Address,
block: Block,
txt: TxtAddr,
group: Group
}
};
};
var A=new Uint8Array([0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2]);
console.log(A,encode(A));
A=new Uint8Array([0x80, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1]);
console.log(A,encode(A));
A=new Uint8Array([0x80, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x1]);
console.log(A,encode(A));
A=new Uint8Array([0x80, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1]);
console.log(A,encode(A));
A=new Uint8Array([0x80, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1]);
console.log(A,encode(A));
A=new Uint8Array([0xa0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1]);
console.log(A,encode(A));
A=new Uint8Array([0x80, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1]);
console.log(A,encode(A));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment