Skip to content

Instantly share code, notes, and snippets.

@nuintun
Created March 8, 2024 06:35
Show Gist options
  • Save nuintun/2e81f3b1a2624959406755d9518ab7f4 to your computer and use it in GitHub Desktop.
Save nuintun/2e81f3b1a2624959406755d9518ab7f4 to your computer and use it in GitHub Desktop.
快速整数转换算法
// 使用位运算将数字转换为8位有符号整数
function toInt8(value: number): number {
return (value << 24) >> 24;
}
// 使用位运算将数字转换为8位无符号整数
function toUint8(value: number): number {
return value & 0xff;
}
// 使用位运算将数字转换为16位有符号整数
function toInt16(value: number): number {
return (value << 16) >> 16;
}
// 使用位运算将数字转换为16位无符号整数
function toUint16(value: number): number {
return value & 0xffff;
}
// 使用位运算将数字转换为32位有符号整数
function toInt32(value: number): number {
return value | 0;
}
// 使用位运算将数字转换为32位无符号整数
function toUint32(value: number): number {
return value >>> 0;
}
// 使用内置方法将数字转换为64位有符号整数
function toInt64(value: bigint): bigint {
return BigInt.asIntN(64, value);
}
// 使用内置方法将数字转换为64位无符号整数
function toUint64(value: bigint): bigint {
return BigInt.asUintN(64, value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment