In TypeScript, the number variable is floating point by default. However, there are situations where it's necessary to restrict the variable to a specific size or type similar to other programming languages. For instance, types like int8, int16, int32, uint8, uint16, and uint32. The approach I've taken involves converting the number to an unsigned integer and performing bitwise operations accordingly. If there are any improvements, better methods, or more efficient ways to achieve this, please share.
export class CONVERT {
static NumberToUint32(x: number): number
{
return x >>> 0;
}
static NumberToUint16(x: number): number
{
return this.NumberToUint32(x) & 0xFFFF;
}
static NumberToUint8(x: number): number
{
return this.NumberToUint32(x) & 0xFF;
}
static NumberToInt32(x: number): number
{
return x >> 0;
}
static NumberToInt16(x: number): number
{
let r: number = 0;
let n = this.NumberToUint16(x);
if(n & 0x8000)
r = 0xFFFF8000 | (n & 0x7FFF);
else
r = n;
return(r);
}
static NumberToInt8(x: number): number
{
let r: number = 0;
let n = this.NumberToUint8(x);
if(n & 0x80)
r = 0xFFFFFF80 | (n & 0x7F);
else
r = n;
return(r);
}
static StrToNumber(val: string, defaultVal: number = 0): number
{
let result: number = defaultVal;
if(!val || val.trim().length == 0)
return result;
// Code for converting string to number
}
}