TS 自定义结构Long与number类型相互转换


TS 自定义结构Long 如下:

export interface Long {

/** Low bits */
low: number;

/** High bits */
high: number;

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

根据给定的 Long 接口定义,我们可以实现 Long 类型与 number 类型之间的相互转换函数。


首先,我们可以编写一个将 Long 转换为 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);
  }
}

上述函数 longToNumber 接受一个 Long 类型的参数 longValue,并根据 unsigned 属性的值,将其转换为相应的 number 类型。如果 unsignedtrue,我们使用无符号右移操作符 >>> 将低位和高位进行组合;如果 unsignedfalse,我们直接将低位和高位进行组合。


接下来,我们可以编写一个将 number 转换为 Long 的函数:

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

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

函数 numberToLong 接受一个 number 类型的参数 numberValue,并根据其值计算出低位和高位。我们使用无符号右移操作符 >>> 取得低位,使用 Math.floor 和除法运算计算出高位。根据 numberValue 的正负值,我们设置 unsigned 属性为相应的布尔值。


现在,我们可以使用上述函数进行 Long 类型和 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 }

在上述示例中,我们首先定义了一个 Long 类型的值 longValue,然后使用 longToNumber 函数将其转换为 number 类型的值 numberValue。接着,我们使用 numberToLong 函数将 numberValue 转换回 Long 类型,并将结果存储在 newLongValue 中。

最后,我们分别打印了 numberValuenewLongValue 的值,验证了转换的准确性。


猜你喜欢

转载自blog.csdn.net/lizhong2008/article/details/135091647
今日推荐