如何将数字转换为 int8、int16、int32、uint8、uint16 或 uint32

Jam*_*mms 6 javascript c# typescript

TypeScript 中的数字变量是浮点型。但是,有时需要将变量限制为类似于其他语言中可用的特定大小或类型。例如,int8、int16、int32、uint8、uint16 和 uint32 类型。我实现的方法将数字转换为无符号整数,并对所需的位执行按位“AND”。根据所需类型是否有符号,它将执行按位“或”。如果有错误,更好的方法,或者更高效的方法,欢迎留言。

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 == null) 
         return result;            
      if(val.length == 0) 
         return result;      
      val = val.trim();
      if(val.length == 0) 
         return(result);
      let sign:number = 1;     
      //
      // . obtain sign from string, and place result in "sign" local varible. The Sign naturally defaults to positive
      //     1 for positive, -1 for negative.
      // . remove sign character from val. 
      //      Note, before the function returns, the result is multiplied by the sign local variable to reflect the sign.
      // . error check for multiple sign characters
      // . error check to make sure sign character is at the head or tail of the string
      //              
      {  
         let positiveSignIndex = val.indexOf('+');
         let negativeSignIndex = val.indexOf('-');
         let nTailIndex = val.length-1;
         //
         // make sure both negative and positive signs are not in the string
         //
         if( (positiveSignIndex != -1) && (negativeSignIndex != -1) ) 
             return result;
         //
         // handle postive sign
         //
         if (positiveSignIndex != -1)
         {
            //
            // make sure there is only one sign character
            //
            if( (positiveSignIndex != val.lastIndexOf('+')) )
             return result;     
             //
             // make sure the sign is at the head or tail
             //
             if( (positiveSignIndex > 0) && (positiveSignIndex < nTailIndex )  )
                 return result;
             //
             // remove sign from string
             //
             val = val.replace("+","").trim();                 
         }    
         //
         // handle negative sign
         //
         if (negativeSignIndex != -1)
         {
            //
            // make sure there is only one sign character
            //
            if( (negativeSignIndex != val.lastIndexOf('-')) )
             return result;     
             //
             // make sure the sign is at the head or tail
             //
             if( (negativeSignIndex > 0) && (negativeSignIndex < nTailIndex )  )
                 return result;
             //
             // remove sign from string
             //
             val = val.replace("-","").trim();  
             sign = -1;                 
         }               
         //
         // make sure text length is greater than 0
         //       
         if(val.length == 0) 
            return result;                             
      }   
      //
      // convert string to a number
      //
      var r = +(<any>val);
      //
      // apply sign if no errors
      //
      if( (r != null) && (!isNaN(r)) )
      {          
         result = r*sign;         
      }
      return(result);    
   }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 0

TypeScript 没有比bigint或更具体的数字类型number,因为 JavaScript 本身没有,并且在基于 JavaScript 的类型系统中本地强制执行它会非常困难。https://github.com/microsoft/TypeScript/issues/4639更详细地介绍了这一点。

如果您仍然非常想强制执行特定的数字类型,那么最好的选择是“品牌类型”,例如https://github.com/kourge/ts-brand提供的类型。品牌数字类型归结为告诉类型系统某些类型别名引用number 以及一些实际上从未存在的“品牌”属性:

type Int32 = number & { __brand: "int32" };
Run Code Online (Sandbox Code Playgroud)

要将值转换为品牌类型,通常需要使用as断言或类型谓词:

const zeroAsInt32 = 0 as Int32;
Run Code Online (Sandbox Code Playgroud)

品牌类型的价值在于,TypeScript 不允许您将任何旧number类型值分配给 type 的内容Int32。您只能指定已“标记”为 的内容int32