程序员人生 网站导航

u128.js 128位无符号整数运算的JavaScript库

栏目:jscript时间:2014-01-26 17:59:41

u128.js 是一个提供 128 位无符号整数运算的 JavaScript 库,旨在兼容各种主流浏览器。

示例代码:

<script type="text/javascript" src="u128.js" ></script>
<script type="text/javascript">

/*
Namespace shorthand
*/
var u = faultylabs.u128;

/*
Conversions to/from hex string:
*/
var a = u.hexval("000000bbaaaaaaaa33333333ffffffff")
var astr = u.hex$(a)
alert( astr == "000000bbaaaaaaaa33333333ffffffff" )

/*
Addition a + b
*/
var a = u.hexval("1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
var b = u.hexval("0000000000000000000000000000001")
var c = u.add(a, b)
alert(u.hex$(c) == "02000000000000000000000000000000")

/*
Subtraction a - b
*/
var a = u.hexval("b0000000000000000000000000000000")
var b = u.hexval("00000000000000000000000000000001")
var c = u.sub(a, b)
alert(u.hex$(c) == "afffffffffffffffffffffffffffffff")

/*
Multiplication a * b
*/
var a = u.hexval("78cd2bbafbd21e3")
var b = u.hexval("de36a45d123b885")
var c = u.mul(a, b)
alert(u.hex$(c) == "0068dbb4c2baf8856f0df18732a6c2ef")

/*
Quotient a / b
*/
var a = u.hexval("0068dbb4c2baf8856f0df18732a6c2ef")
var b = u.hexval("de36a45d123b885")
var c = u.div(a, b)
alert(u.hex$(c) == "0000000000000000078cd2bbafbd21e3")

/*
Remainder a % b
*/
var a = u.hexval("00000521aaaaaaa76666666bfffffff9")
var b = u.hexval("00000521aaaaaaa00000000000000000")
var c = u.mod(a, b)
alert(u.hex$(c) == "00000000000000076666666bfffffff9")

/* Comparison of a and b
0 -> a == b
1 -> a > b
-1 -> a < b
*/
var a = u.hexval("de36a45d123b885")
var b = u.hexval("68dbb4c2baf8856f0df18732a6c2ef")
var cmp = u.cmp(a, b)
alert(cmp == -1)

/*
Binary AND a & b
Binary OR a | b
Binary XOR a ^ b
Binary NOT ~a
*/
var v55 = u.hexval("55555555555555555555555555555555")
var vAA = u.hexval("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
var vFF = u.hexval("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
var vOR = u.or (v55, vAA)
var vAND = u.and(vFF, v55)
var vXOR = u.xor(vFF, v55)
var vNOT = u.not(v55)
alert(u.hex$(vOR) == "ffffffffffffffffffffffffffffffff")
alert(u.hex$(vAND) == "55555555555555555555555555555555")
alert(u.hex$(vXOR) == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
alert(u.hex$(vNOT) == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

/*
Left shift
*/
var a = u.hexval("00BBAAAAAAAA33333333FFFFFFFF")
var la = u.shl(a, 8)
alert(u.hex$(la) == "0000bbaaaaaaaa33333333ffffffff00")

/*
Right shift
*/
var a = u.hexval("0000BBAAAAAAAA33333333FFFFFFFF11")
var ra = u.shr(a, 8)
alert(u.hex$(ra) == "000000bbaaaaaaaa33333333ffffffff")

/*
Bit test
*/
var a = u.hexval("10000000000000000000000")
var bit = u.btest(a, 88)
alert(bit == 1)

/*
Shortcuts for the values 1 and 0
*/
var a = u.zero()
var b = u.one()
alert(
u.hex$(a) == "00000000000000000000000000000000" &&
u.hex$(b) == "00000000000000000000000000000001"
)

</script>
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐