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 Long
interface definition, we can implement the conversion function between Long
types and types.number
First, we can write a function that Long
converts 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 longToNumber
accepts a Long
parameter of type longValue
and unsigned
converts it to the corresponding number
type based on the value of the attribute. If unsigned
is true
, we use the unsigned right shift operator >>>
to combine the low bits and high bits; if unsigned
is false
, we directly combine the low bits and high bits.
Next, we can write a function that number
converts 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 numberToLong
accepts a number
parameter of type numberValue
and calculates the low and high bits based on its value. We use the unsigned right shift operator >>>
to get the low bits, Math.floor
and the and division operations to calculate the high bits. Depending on numberValue
the positive or negative value of , we set unsigned
the property to the corresponding Boolean value.
Now, we can use the above functions to convert between Long
types 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 Long
value of type longValue
and then use longToNumber
the function to convert it to number
a value of type numberValue
. Next, we use numberToLong
the function to numberValue
convert back to Long
type and store the result in newLongValue
.
Finally, we printed the values of numberValue
and respectively newLongValue
to verify the accuracy of the conversion.