TS custom structure Long and number type conversion


TS custom structure Long is as follows:

export interface Long {

/** Low bits */
low: number;

/** High bits */
high: number;

/** Whether unsigned or not */
unsigned: boolean;
} 

According to the given Longinterface definition, we can implement the conversion function between Longtypes and types.number


First, we can write a function that Longconverts to :number

function longToNumber(longValue: Long): number {
  const { low, high, unsigned } = longValue;

  if (unsigned) {
    return (high >>> 0) * 4294967296 + (low >>> 0);
  } else {
    return high * 4294967296 + (low >>> 0);
  }
}

The above function longToNumberaccepts a Longparameter of type longValueand unsignedconverts it to the corresponding numbertype based on the value of the attribute. If unsignedis true, we use the unsigned right shift operator >>>to combine the low bits and high bits; if unsignedis false, we directly combine the low bits and high bits.


Next, we can write a function that numberconverts to :Long

function numberToLong(numberValue: number): Long {
  const low = numberValue >>> 0;
  const high = Math.floor(numberValue / 4294967296);

  return {
    low,
    high,
    unsigned: numberValue < 0 ? true : false,
  };
}

The function numberToLongaccepts a numberparameter of type numberValueand calculates the low and high bits based on its value. We use the unsigned right shift operator >>>to get the low bits, Math.floorand the and division operations to calculate the high bits. Depending on numberValuethe positive or negative value of , we set unsignedthe property to the corresponding Boolean value.


Now, we can use the above functions to convert between Longtypes and types.number

const longValue: Long = {
  low: 1234567890,
  high: 0,
  unsigned: false,
};

const numberValue = longToNumber(longValue);
console.log(numberValue); // 输出: 1234567890

const newLongValue = numberToLong(numberValue);
console.log(newLongValue); // 输出: { low: 1234567890, high: 0, unsigned: false }

In the above example, we first define a Longvalue of type longValueand then use longToNumberthe function to convert it to numbera value of type numberValue. Next, we use numberToLongthe function to numberValueconvert back to Longtype and store the result in newLongValue.

Finally, we printed the values ​​of numberValueand respectively newLongValueto verify the accuracy of the conversion.


Supongo que te gusta

Origin blog.csdn.net/lizhong2008/article/details/135091647
Recomendado
Clasificación