Created
November 12, 2020 06:33
-
-
Save envis10n/e52a558999e6257908271233256b2606 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function wrap(value: number, max: number, min: number): number { | |
while (value > max || value < min) { | |
value = value > max ? value - (max + 1) : value < min ? value + (max + 1) : value; | |
} | |
return value; | |
} | |
function wrap_u8(value: number = 0): number { | |
return wrap(value, 255, 0); | |
} | |
function wrap_u16(value: number = 0): number { | |
return wrap(value, 65535, 0); | |
} | |
function split_u16(u: u16): [u8, u8] { | |
let v = u.cast(); | |
let v1 = v >> 8; // first section | |
let vo = v1 << 8; // add 0 bytes | |
let v2 = vo ^ v; // last section; | |
return [new u8(v1), new u8(v2)]; | |
} | |
export class u16 extends Number { | |
constructor(value?: number) { | |
super(wrap_u16(value)); | |
} | |
public add(value: number): u16 { | |
return new u16(this.valueOf() + value); | |
} | |
public sub(value: number): u16 { | |
return new u16(this.valueOf() - value); | |
} | |
public neg(): u16 { | |
return new u16(-this.valueOf()); | |
} | |
public clone(): u16 { | |
return new u16(this.valueOf()); | |
} | |
public static MAX(): u16 { | |
return new u16(65535); | |
} | |
public static MIN(): u16 { | |
return new u16(); | |
} | |
public static from_be(be: [u8, u8]): u16 { | |
return u16.from_le([be[1], be[0]]); | |
} | |
public static from_le(le: [u8, u8]): u16 { | |
const hi = le[1].toString(16); | |
const lo = le[0].toString(16); | |
return new u16(parseInt(`${lo}${hi}`, 16)); | |
} | |
public split(): [u8, u8] { | |
return split_u16(this); | |
} | |
public as_u8(): u8 { | |
return new u8(this.valueOf()); | |
} | |
public cast(): number { | |
return this as unknown as number; | |
} | |
} | |
export class u8 extends Number { | |
constructor(value?: number) { | |
super(wrap_u8(value)); | |
} | |
public static MAX(): u8 { | |
return new u8(255); | |
} | |
public static MIN(): u8 { | |
return new u8(); | |
} | |
public add(value: number): u8 { | |
return new u8(this.valueOf() + value); | |
} | |
public sub(value: number): u8 { | |
return new u8(this.valueOf() - value); | |
} | |
public neg(): u8 { | |
return new u8(-this.valueOf()); | |
} | |
public clone(): u8 { | |
return new u8(this.valueOf()); | |
} | |
public as_u16(): u16 { | |
return u16.from_le([u8.MIN(), this]); | |
} | |
public cast(): number { | |
return this as unknown as number; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment